TDD: How to test domain model

domain-modeltddtest-coverage

When practicing TDD, how do you test a domain model? If you don't test, how do you account for code coverage? We want to have 100% coverage (or as much as possible), but despite hours of training videos we cannot find the best solution.

UPDATE: Given a domain model I want to write of User which has properties: Id (primary key), FirstName, LastName, tenantId(foreign key). Do you prefer to just create this model without test coverage? If so, then you start your project with 0% code coverage, right? Then you are getting off to a rough start. But in pure TDD, you should not write code without a test. So what would you do?

Let's take this a step further. What if you have behavior–but just a little? Now your User has Id (primary key), FirstName, LastName, tenantId (foreign key) and birthDate. Then you have a method/function to calculate age based on birthdate. I feel that I should write tests before the age calculation, but not before the model. How would you account for this paradox?

Best Answer

This is why code coverage is a terrible metric.

If you have a simple DTO (a class with only properties that contains data), there is very little value in testing the methods that get and set those properties. You can, and your code coverage will surely go up, but it's a useless test. You're testing the language and not the code. If you strive for a good coverage, strive for coverage of code that actually does something.

The 'only write code to make a failing test pass' is a very good rule, but it is not meant to be invoked at every turn. In fact, even constructors are evil so we probably should never use them, right? Well, not really. But it is a lot easier (and catchier) to say 'never' instead of 'mostly never, unless...'. The rule that you should never write code unless it is written to make a failing test pass is the same.

With time and application of TDD to your development comes an amount of experience with it that allows you to see where the rule should be enforced and where it should not be enforced.

Related Topic