Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a UT to mock an internal object in one method?

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.

like image 419
Smartmarkey Avatar asked Sep 16 '11 06:09

Smartmarkey


2 Answers

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.

like image 95
datalost Avatar answered Sep 26 '22 21:09

datalost


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".

like image 29
murrekatt Avatar answered Sep 26 '22 21:09

murrekatt