For example , I have a java class as below. I am going to write a unit test for doWork(), so I would like to control obj's behavior. But it is obvious that obj is instantiated internally.
How can I write this UT? Now I am using Junit+Mockito.
class ToBeTest{
public ToBeTest(){}
public boolean doWork(){
OtherObject obj=new OtherObject();
return obj.work();
}
}
Thanks in advance. :)
BTW, The reality is I am writing UT for other person's class. So I don't want to change it. It has been fully tested by integration test.
The best way is to write code to support testing (Test-Driven Development is emphasizing this). At the moment, your code is written in the way which makes it difficult to test.
Please consider using dependency injection, because it helps you mock the dependent object.
This is a classical example where you should use dependency injection.
In short, instead of creating the object (dependency) internally, you pass it in the constructor or use a factory to create what you want (the factory returns the real implementation in production code and another in test). This gives you the possibility to change the implementation when you test.
Look at the examples following the like I provided or google for "Java dependency injection example".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With