简体   繁体   中英

How can I test this method using Mockito?

I have a method with complex interaction between different objects that I would like to test using the Mockito framework. I would appreciate some guidelines. I know the code does not mean much.

Both getInstance() methods are static. I would like to mock obj3 and make the if statement to return true in the test.

public MyRequest getRequest(ObjectOne obj1, ObjectTwo obj2) {

    ObjectThree obj3 = FactoryOne.getInstance().getList().getObject(obj2.getId());


    if(FactoryTwo.getInstance().isFlagSet("flag")){
        ....
    }


    return new MyRequest(....);
}

Actually, the method invoked to value the obj3 variable is not straight testable.

The root cause is getInstance() that is a static method.

In fact, FactoryOne.getInstance() should be a dependency of the class under test and the returned object should be an interface

In this way, you can define a constructor that sets the dependency:

public MyClass(FooInterface foo){
   this.foo = foo;
}

And replace :

ObjectThree obj3 = FactoryOne.getInstance().getList().getObject(obj2.getId());

by :

ObjectThree obj3 = foo.getList().getObject(obj2.getId());

In the application code, you could invoke the constructor :

MyClass c = new MyClass(FactoryOne.getInstance().getList());

And in the test code, you could create a mock for the Foo interface, set it to the class under the test via the constructor :

Foo fooMock = Mockito.mock(Foo.class);
MyClass myClassUnderTest = new MyClass(fooMock);

Then record a mock behavior for getList() to return another mocked object with the desired value for the invocation to getObject() in the test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM