I have an application service which returns entity by its registration number
public Entity FindByRegNumber(string number)
{
if (!RegNumber.IsValid(number))
{
return null;
}
var regNumber = new RegNumber(regNumber);
return repository.FindBy(regNumber);
}
Here RegNumber
is a value object and it has static method IsValid
which verifies that string correctly represents registration number. This method is used inside constructor as well, but, if string is not valid, constructor throws InvalidOperationException
.
If IsValid
method belonged to some injected dependency, I could just check in my test that IsValid
was called (a kind of white box testing). Now I have to test FindByRegNumber
repeating all the input used for testing IsValid
method (black box testing).
It looks like the only reason to get rid of static method is to make testing easier. It does not even decreases coupling while call to FullRegistrationNumber
constructor stays.
Another approach is to introduce a factory FullRegistrationNumberCreator' which could abstract away both validation and construction of
FullRegistrationNumber`, but it seems like an overkill and overengineering.
Is here a correct solution?
Assert.DoesNotThrow<InvalidOperationException>(() => yourClass.FindByRegNumber('123'))
? Also you use domain-driven-design, so I recommend revisiting your ubiqitous language with your business experts to see ifFindByRegNumber
is a business choice for the problem domain to make it more ubiqitous like:FindEntityByRegistrationNumber
or so.null
. And In my test I need then only provide some invalid input to check this branch of execution.RegNumber
, not astring
. Make use of your type system, it's there exactly for this reason, to help you prevent passing bad data. If you can't construct an invalidRegNumber
, you don't have to ensure it is valid every time it is passed to a function.