0

There is a final static member in class ToBeTestClass:

protected final static LMSServiceHelper externalService;

I mock it with

@Mock
protected LMSServiceHelper externalService;

Then I want to get different values in different test methods:

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

However, I can't get "bbb" or "ccc" whereas always get "aaa". It seems when I set the return value first time, and it will never changes.

Anyone has met this?

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
csujiabin
  • 81
  • 1
  • 10
  • Could you please give a **full** [mcve]. And alone the idea of using a **static** field in in inheritance context (protected) ... sounds strange. I would rather look into changing production code here. – GhostCat Sep 21 '17 at 04:23

2 Answers2

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?

csujiabin
  • 81
  • 1
  • 10
0

Reset your mocked object as shown below then you will see different values

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

}

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

}


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

    Mockito.reset(externalService);

}
Praveen Kumar Mekala
  • 628
  • 1
  • 10
  • 26