mogoli
mogoli

Reputation: 2395

Mocking a method that uses external classes, mockito

I'm new to mockito and just trying to understand how it works.

I have a method that I want to test. The method instantiates multiple classes to use its methods.

e.g.

methodToTest{
 class1 c1 = new class1();
 class2 c2 = new class2();
 class3 c4 = new class3();

c1.method1;
c2.method2;
c3.method3;

more logic 

...

return result
}

I understand that in order to test this method I need to mock the classes. Doe this mean I need to decouple it and pass in each class as a parameter to the method? I want to avoid having a method that uses a large list of parameters that will only really be necessary when mocking.

Perhaps I've missed something.

Thanks for your insights.

Upvotes: 3

Views: 5361

Answers (2)

Paras Mittal
Paras Mittal

Reputation: 1149

Instead of passing different objects of classes to method you could actually mock when new object is created. eg

Class1 class1 = Mockito.mock(Class1.class);
PowerMockito.whenNew(Class1.class).withNoArguments().thenReturn(class1);

At the top of the test class write this annotation

@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class})
public class Class1Test {

----------- some code-------
}

Follow the link https://code.google.com/p/powermock/wiki/MockitoUsage13

Hope this will solve your problem. Ask in case of query.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328870

My standard solution here is to add a method which instantiates the class:

public ClassToTest {
    methodToTest{
        class1 c1 = newClass1();
        ...
    }

    class1 newClass1() {
        return new Class1();
    }
}

The new method is protected or package private and I simply override it in my unit test to inject the mocks:

@Test
public void testFoo() {
    ClassToTest inst = new ClassToTest() {
        class1 newClass1() {
            return new Class1(); // <--- you can mock here
        }            
    };
}

Upvotes: 3

Related Questions