When unit testing a service, I tend to have a base class where I do all the setting up/initialisation. For each method in the service, I’d have a separate unit test class which derives from the base class. For example, if I want to unit test two methods GetAllNews and GetNewsById in SampleNewsService, I’ll have a SampleNewsServiceTestsBase where I initialise the service with all its required dependencies. I then have a separate unit test class derived from SampleNewsServiceTestsBase to test all scenarios for each of the method in the SampleNewsService.
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public class SampleNewsServiceTestsBase { [SetUp] public void SetUp() { // Service initialisation and other setups } } }
Base class – SampleNewsServiceTestsBase.cs
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public class GetNewsByIdTests : SampleNewsServiceTestsBase { [Test] public void SampleTest() { // Test logic goes here } } }
Tests for GetNewsById method – GetNewsByIdTests.cs
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public class GetAllNewsTests : SampleNewsServiceTestsBase { [Test] public void SampleTest() { // Test logic goes here } } }
Tests for GetAllNews method – GetAllNewsTests.cs
This way has been working well for me but recently I come across another way to organise unit tests which I think is quite nice. This is by adding unit tests for each method as a partial class to the base class. I would rename the base class to SampleNewsServiceTests as this makes more sense and that there are no more derived classes. The unit tests then look like the following.
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public partial class SampleNewsServiceTests { [SetUp] public void Setup() { // Service initialisation and other setups } } }
The setup or ‘base’ class – SampleNewsServiceTests.cs
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public partial class SampleNewsServiceTests { [Test] public void GetNewsByIdSampleTest() { // Test logic goes here } } }
Tests for GetNewsById method – SampleNewsServiceTests.GetNewsById.cs
using NUnit.Framework; namespace SampleWebApplicationTests { [TestFixture] public partial class SampleNewsServiceTests { [Test] public void GetAllNewsSampleTest() { // Test logic goes here } } }
Tests for GetAllNews method – SampleNewsServiceTests.GetAllNews.cs
I would suggest using an extension for Visual Studio like File Nesting to nest all the method test files under the setup file to keep the solution cleaner.
Conclusion
I honestly don’t have a preference between the two ways. These two ways are very similar in a way. It doesn’t matter which way you go with though, just pick one and stick with it. The only thing I think partial class way does better is that you don’t have any derived test classes – composition over inheritance.