niedziela, 11 września 2016

Unit Testing and NullArgumentException Assertions

One of the coolest things about TDD is that you don't have to write any code before you know the reason, and some reasons can be quite trivial... Like the NullArgumentException checks on constructor. I really like the idea of Fail-fast design so I can watch debugger less often so I always do those assertions. How does it look for average middle layer class?

Part of RpcClientTest.cs

And this is alright, you can clearly see what those tests are for and they serve a good purpose. But wait. Can we do it shorter? Can it take less time? When I modify parameters on ctor I'll have to change all of them.

Now don't be sad. Wanna do it that way?

Part of RpcClientTest.cs after change

Hold on. How does it work?

Well quite simply. Method ThrowsOnAnyNullArgument takes class Type as generic parameter and array of valid, ordered params that will let constructor be invoked correctly. Behind the scenes appropriate constructor of given Type is selected, based on number and Type of parameters. After that it is being invoked for each given parameter to check if replacing current one with null will throw NullArgumentException.

That replaces three tests with just one still doing its job properly. Here's first version of it's code with covering tests.

ConstructorAssertTest.cs

ConstructorAssert.cs