Organising unit tests into partial classes

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.

Base class – SampleNewsServiceTestsBase.cs

Tests for GetNewsById method – GetNewsByIdTests.cs

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.

The setup or ‘base’ class – SampleNewsServiceTests.cs

Tests for GetNewsById method – SampleNewsServiceTests.GetNewsById.cs

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.

Like this post?

Leave a Reply

Your email address will not be published. Required fields are marked *