Issues with testing Spring's declarative caching support on a Spring data repository

☆樱花仙子☆ 提交于 2019-11-29 11:28:24

Your memberRepositoryMock that you try to use in when() is already a bean with cache advice around.

do something like this (I don't especially like the static member, but seems less ugly than getting advised bean using spring internals):

// this is actuall mock
private static MemberRepository myMock = mock(MemberRepository.class);

// this is mock wrapped behind cache
@Autowired
private MemberRepository memberRepositoryMock;

@Before
public void setup() {
    // using real mock for mockito stuff
    reset(myMock); // needed for tests where spring config is cached (= mock is not recreated between tests)
    when(myMock.findByEmail(eq("foo@foo.com"))).thenReturn(MEMBER_ONE);//NPE Here
    when(myMock.findByEmail(eq("bar@bar.com"))).thenReturn(MEMBER_TWO);
}

@Test
public void testFindByEmail() {
    // using adviced bean in test
    Member firstInvocation = memberRepositoryMock.findByEmail("foo@foo.com");
    assertThat(firstInvocation, is(MEMBER_ONE));

    Member secondInvocation = memberRepositoryMock.findByEmail("foo@foo.com");
    assertThat(secondInvocation, is(MEMBER_ONE));

    // again real mock, not bean here
    verify(myMock, times(1)).findByEmail("foo@foo.com");
}

@Profile(Profiles.TEST)
@Configuration
static class Config {

    @Bean
    public MemberRepository memberRepositoryMock() {
        return myMock;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!