Unit testing value objects in isolation from its dependencies

前端 未结 3 2030
刺人心
刺人心 2021-01-14 01:39

TL;DR
How do you test a value object in isolation from its dependencies without stubbing or injecting them?


In Misko Hevery\'s blog post T

3条回答
  •  天涯浪人
    2021-01-14 02:03

    Your scenario can also be applied to entities. There are cases where an entity requires some dependency in order to perform some behaviour. As far as I can tell the most popular mechanism to use is double-dispatch.

    I'll use C# for my examples.

    In your case you could have something like this:

    public void Validate(IQuantityValidator validator)
    

    As other answers have noted a value object is typically simple enough to perform its invariant checking in the constructor. An e-mail value object would be a good example as an e-mail has a very specific structure.

    Something a bit more complex could be an OrderLine where we need to determine, totally hypothetical, whether it is, say, taxable:

    public bool IsTaxable(ITaxableService service)
    

    In the article you reference I would assert that the 'newable' relates quite a bit to the 'transient' type of life cycle that we find in DI containers as we are interested in specific instances. However, when we need to inject specific values the transient business does not really help. This is the case for entities where each is a new instance but has very different state. A repository would hydrate the object but it could just as well use a factory.

    The 'true' dependencies typically have a 'singleton' life-cycle.

    So for the 'newable' instances a factory could be used if you would like to perform validation upon construction by having the factory call the relevant validation method on your value object using the injected validator dependency as Mark Seemann has mentioned.

    This gives you the freedom to still test in isolation without coupling to a specific implementation in your constructor.

    Just a slightly different angle on what has already been answered. Hope it helps :)

提交回复
热议问题