Miles Peterson
Miles Peterson

Reputation: 265

Controlling method output with Mockito

Say I have a class like this:

public class RegularStuff {

    public int getAmountOfStuff() {

        int stuff = getAmount();
        return stuff;
    }

    public int getAmount() {
        return 10;
    }
}

Now let's say I have a unit test like so:

@RunWith(PowerMockRunner.class)
public class StuffTest {

    private RegularStuff testobject;

    @Before
    public void setUp() {
        testObject = new RegularStuff();
    }

    @Test
    public void testGetAmountOfStuff() {
        int result = testObject.getAmountOfStuff();
        assertEquals(5, result);
    }
}

Note that the above assertion is invalid. It will fail because the method getAmountOfStuff calls another method that always returns 10. I split these up to make the code simpler to analyze. It might seem trivial given this example, but I often find myself creating much larger methods. Thus, I split up code in a given function. Otherwise the sheer amount of text becomes too big/confusing to analyze or fix- let alone test.

So what I need to know is how to control the output of certain methods in the class I'm testing.

Upvotes: 0

Views: 134

Answers (1)

kswaughs
kswaughs

Reputation: 3087

1) To mock a public method, below is the test method.

@RunWith(PowerMockRunner.class)
public class StuffTest {

private RegularStuff testObject;

@Before
public void setUp() {
    testObject = PowerMockito.mock(RegularStuff.class, Mockito.CALLS_REAL_METHODS);
    // The reason using CALLS_REAL_METHODS is that we are both testing & mocking same object.
}

// test by mocking public method
@Test
public void testGetAmountOfStuff() {

    PowerMockito.when(testObject.getAmount()).thenReturn(5);

    int result = testObject.getAmountOfStuff();
    Assert.assertEquals(5, result);
}

}

2) If your getAmount() is private method, Below is the test method to mock a private method.

@RunWith(PowerMockRunner.class)
@PrepareForTest(RegularStuff.class)
public class StuffTest {

private RegularStuff testObject;

@Before
public void setUp() {
    testObject = PowerMockito.mock(RegularStuff.class, Mockito.CALLS_REAL_METHODS);
    // reason using CALLS_REAL_METHODS, we are both testing & mocking same object.
}

// test by mocking private method
@Test
public void testByMockingPrivateMethod() throws Exception{

    PowerMockito.doReturn(5).when(testObject , "getAmount" );
    int result = testObject.getAmountOfStuff();
    Assert.assertEquals(5, result);
 }
}

Upvotes: 1

Related Questions