0

假设我有这样的课程:

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 的方法。我将它们分开以使代码更易于分析。鉴于这个例子,它可能看起来微不足道,但我经常发现自己创建了更大的方法。因此,我在给定的函数中拆分了代码。否则,大量的文本会变得太大/令人困惑,无法分析或修复——更不用说测试了。

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

4

1 回答 1

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);
 }
}
于 2015-10-16T05:11:35.487 回答