Welcome to TDD Addict - a blog about test-driven development and related topics!

Every so often we all stumble upon various challenges related to unit testing. I hope that I can help others with improving their TDD skills by sharing my random thoughts and experiences with you.

Feel free to send me an email if you have any comments, questions or requests.

Wednesday, August 9, 2017

Test setup readability in C# 7

How do you set up the state and the data that you need in tests? Say that you are writing a view class for a domain object. In addition, you need to set up a mock environment that you need to assert against in order to make sure that the view is making the correct calls to environment (which might be a graphics card, a web service or a UI frontend:

With NUnit, you can decorate setup methods with the [SetUp] or [SetUpFixture] attribute. These methods will be run before the tests or test class, allowing you to create data and set this as fields in the test class. A test class might look like this:

This quickly becomes messy if multiple objects are created. If they depend on each other, it becomes even more messy.

C#7 has a new feature that is very handy for this scenario: return tuples! With return tuples, you can create and initialise everything in one reusable method. Everything is still type safe and very readable:

Various tests in the test class may or may not reference the objects that are returned. For readability, simply assign the ignored return variables to a dummy underscore variable if you don't need them in the tests: