Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faking constructors for unit testing

I have a set of classes that have dependencies at instantiation time, that is, when creating an object of type A, it also creates another of type B, which subsequently creates others of type C, etc.

For testing matters, I don't need the whole functionality of all the levels to test the upper ones, so I could use stubs or mocks, but as I have explicit new's in the constructors I cannot see a direct way other than changing the code to use an AbstractFactory and provide one that creates the fakes at testing time.

So, is there any "black magic" way to hack the Java class loader so the fake testing classes are created instead the normal ones when instantiating objects with new?

Thanks!

like image 803
fortran Avatar asked Feb 15 '26 11:02

fortran


1 Answers

Why not add a constructor which takes those dependencies as parameters, instead of creating them yourself in the constructor? Personally I'd add that one and remove the other one :) Injecting the dependencies makes the code easier to test and more flexible in the future (as you can easily inject a different implementation later on, without changing the code.)

like image 120
Jon Skeet Avatar answered Feb 18 '26 01:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!