用Mockito输出控制方法

时间:2015-10-15 16:44:33

标签: java unit-testing methods mocking powermockito

说我有这样的课程:

public class RegularStuff {

    public int getAmountOfStuff() {

        int stuff = getAmount();
        return stuff;
    }

    public int getAmount() {
        return 10;
    }
}

现在让我们说我有一个单元测试:

@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);
    }
}

请注意,上述断言无效。它将失败,因为方法getAmountOfStuff调用另一个始终返回10的方法。我将它们拆分以使代码更易于分析。考虑到这个例子,这似乎微不足道,但我经常发现自己创造了更大的方法。因此,我在给定的函数中分割代码。否则,大量的文本变得太大/混乱,无法分析或修复 - 单独测试。

所以我需要知道的是如何控制I类测试中某些方法的输出。

1 个答案:

答案 0 :(得分:1)

1)要模拟公共方法,下面是测试方法。

@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)如果你的getAmount()是私有方法,下面是模拟私有方法的测试方法。

@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);
 }
}