Java – constructor for masquerading unit tests

I have a set of classes with dependencies when instantiating, that is, when creating an object of type A, it also creates another type B, and then creates other classes of type C, and so on

For testing problems, I don't need all the functions at all levels to test the upper layer, so I can use stub or simulation. However, because I have a clear new method in the constructor, I can't see a direct method to use AbstractFactory and provide a method to create fake goods during testing

So, is there any "black magic" method to crack the Java class loader to create a fake test class instead of a normal test class when instantiating an object with new?

thank you!

Solution

Why not add a constructor that takes these dependencies as parameters instead of creating them yourself in the constructor? I will personally add one and remove the other:) injecting dependencies makes the code easier to test and more flexible in the future (because you can easily inject different implementations later without changing the code.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>