简体   繁体   中英

PowerMockito thenReturn returns wrong object

I'm using PowerMockito to mock a static cache in my tests. In general, the cache works like this:

Cache.getInstance().findEntityById(AbstractDTO);
// so, if I want a TypeA, I use:
TypeADTo typeADTO = // go the dto from the db ...
TypeA = Cache.getInstance().findEntityById(typeADTO);

The static cache is widly used in the application. So to use it in unit tests, I use:

    PowerMockito.mockStatic( Cache.class );
    final Cache mockedCache = PowerMockito.mock( Cache.class );
    PowerMockito.when( Cache.getInstance() ).thenReturn( mockedCache );
// mock all I want to get
  TypeA typeA = new TypeA(some parameters);
  TypeB typeB = new TypeB(some parameters);

PowerMockito.when(
        Cache.getInstance().findEntityByBusinessId(
                Mockito.any( TypeADTO.class ) ) ).thenReturn( typeA );
PowerMockito.when(
        Cache.getInstance().findEntityByBusinessId(
                Mockito.any( TypeADTO.class ), Mockito.anyBoolean() ) )
        .thenReturn( typeA );


PowerMockito.when(
        Cache.getInstance().findEntityByBusinessId(
                Mockito.any( TypeBDTO.class ) ) ).thenReturn(
        tybeB );
PowerMockito.when(
        Cache.getInstance().findEntityByBusinessId(
                Mockito.any( TypeBDTO.class ), Mockito.anyBoolean() ) )
        .thenReturn( typeB );

I created some mock statements for all needed types. (As you can see there is more than one method which need to be mocked for one type)

The problem is: power mockito always returns the object which was set in the last PowerMockito.when(...) statement.

Have you tried chaining the calls?, also, you can use the Mockito's when word.

Mockito.when(Cache.getInstance().findEntityByBusinessId(any(TypeBDTO.class),anyBoolean()))
       .thenReturn( typeA )
       .thenReturn( typeB );

This will record the mock exactly in that order.

A whole example for future reference:

@RunWith(PowerMockRunner.class)
@PrepareForTest({BusinessUtility.class})
public class BusinessUtilityTest {

    @Before
    public void setUp() {
        PowerMockito.mockStatic(BusinessUtility.class);
    }

    @Test
    public void testStatic() {
        when(BusinessUtility.getDate())
                         .thenReturn(new Date(1111))
                         .thenReturn(new Date(2222));

        assertThat(BusinessUtility.getDate()).hasTime(1111);
        assertThat(BusinessUtility.getDate()).hasTime(2222);
    }
}

Hints:

  • Use static imports to make your code more readable
  • Use PowerMockito just to initialize your Static classes, then, keep using Mockito consistently
  • Avoid as much as possible static classes, testing is harder, as you can see ;)

EDIT ----------------------------------------------

Take a look a this example, is similar to your current use case:

Class:

static class BusinessUtility {
    public static <T> T getObject(T instance) {
        return null;
    }

    public static <T> T getObject(T instance, Boolean b) {
        return null;
    }
}

Test:

@Test
public void testStatic() {
    //arrange
    when(BusinessUtility.getObject(anyString()))
            .thenReturn("one")
            .thenReturn("two");

    when(BusinessUtility.getObject(any(Date.class), anyBoolean()))
            .thenReturn(new Date(1111))
            .thenReturn(new Date(2222));

    //act
    String firstStr = BusinessUtility.getObject("asdf");
    String secondStr = BusinessUtility.getObject("qwerty");

    Date firstDate = BusinessUtility.getObject(new Date(), true);
    Date secondDate = BusinessUtility.getObject(new Date(), false);

    //assert
    assertThat(firstStr).isEqualTo("one");
    assertThat(secondStr).isEqualTo("two");

    assertThat(firstDate).isEqualTo(new Date(1111));
    assertThat(secondDate).isEqualTo(new Date(2222));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM