Mockito / PowerMockito:模拟最终静态成员不能在不同方法中返回不同的值

时间:2017-09-20 19:32:32

标签: mockito

班级final static中有ToBeTestClass个成员:

protected final static LMSServiceHelper externalService;

我用

模仿它
@Mock
protected LMSServiceHelper externalService;

然后我想在不同的测试方法中得到不同的值:

public void testMethod1() {
    PowerMockito.when(externalService.getSomething).thenReturn("aaa");
}

public void testMethod2() {
    PowerMockito.when(externalService.getSomething).thenReturn("bbb");
}

public void testMethod3() {
    PowerMockito.when(externalService.getSomething).thenReturn("ccc");
}

然而,我无法获得" bbb"或" ccc"而总是得到" aaa"。当我第一次设置返回值时,它似乎永远不会改变。

有人见过吗?

2 个答案:

答案 0 :(得分:1)

@Before
public void setUp() {
    Mockito.when(externalService.getSomething)
           .thenReturn("aaa")
           .thenReturn("ccc")
           .thenReturn("ccc"); //any subsequent call will return "ccc"
}

How to tell a Mockito mock object to return something different the next time it is called?

答案 1 :(得分:0)

重置您的模拟对象,如下所示,您将看到不同的值

update

}

public void testMethod1() {
PowerMockito.when(externalService.getSomething).thenReturn("aaa");
Mockito.reset(externalService);
相关问题