Unit testing factory methods which have a concrete class as a return type

前端 未结 5 436
醉梦人生
醉梦人生 2020-12-15 03:35

So I have a factory class and I\'m trying to work out what the unit tests should do. From this question I could verify that the interface returned is of a particular concret

5条回答
  •  粉色の甜心
    2020-12-15 03:49

    If the factory is returning concrete types, and you're guaranteeing that your factory always returns a concrete type, and not null, then no, there isn't too much value in the test. It does allows you to make sure, over time that this expectation isn't violated, and things like exceptions aren't thrown.

    This style of test simply makes sure that, as you make changes in the future, your factory behaviour won't change without you knowing.

    If your language supports it, for your dependencies, you can use reflection. This isn't always the easiest to maintain, and couples your tests very tightly to your implementation. You have to decide if that's acceptable. This approach tends to be very brittle.

    But you really seem to be trying to separate which classes are constructed, from how the constructors are called. You might just be better off with using a DI framework to get that kind of flexibility.

    By new-ing up all your types as you need them, you don't give yourself many seams (a seam is a place where you can alter behaviour in your program without editing in that place) to work with.

    With the example as you give it though, you could derive a class from the factory. Then override / mock CreateADependency(), CreateAnotherDependency() and CreateAThirdDependency(). Now when you call CreateSomeClassWithDependencies(), you are able to sense whether or not the correct dependencies were created.

    Note: the definition of "seam" comes from Michael Feather's book, "Working Effectively with Legacy Code". It contains examples of many techniques to add testability to untested code. You may find it very useful.

提交回复
热议问题