如何模拟CrudRepository调用?

dan*_*ves 5 java spring mocking spring-mvc mockito

我正在尝试在Spring MVC应用程序上进行简单的控制器测试

我有这个测试班

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, WebAppConfig.class})
@WebAppConfiguration
public class NotificacaoControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private NotificacaoRepository notificacaoRepositoryMock;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        //We have to reset our mock between tests because the mock objects
        //are managed by the Spring container. If we would not reset them,
        //stubbing and verified behavior would "leak" from one test to another.
        Mockito.reset(notificacaoRepositoryMock);

        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void add_NewTodoEntry_ShouldAddTodoEntryAndRenderViewTodoEntryView() throws Exception {
        Notificacao added = new Notificacao(123,"resource","topic", "received", "sent");

        when(NotificacaoRepository.save( added )).thenReturn(added);
Run Code Online (Sandbox Code Playgroud)

我的TestContext类有这个bean

@Bean
public NotificacaoRepository todoService() {
    return Mockito.mock(NotificacaoRepository.class);
}
Run Code Online (Sandbox Code Playgroud)

而我的仓库就是

public interface NotificacaoRepository extends CrudRepository<Notificacao, Long> {
}
Run Code Online (Sandbox Code Playgroud)

但它甚至都没有编译,我不断收到“ 无法在最后一行”中的类型CrudRepository中 “对静态方法save(Notificacao)进行静态引用when(NotificacaoRepository.save(added))

我在此链接http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/的示例中看到了这种用法,但他在那里使用了一项服务类,这与使用CrudRepository并不完全相同。

我试图找到一个如何测试CrudRepository实现的示例,但没有找到一个示例,因此我认为这应该像其他模拟游戏一样简单

小智 2

由于保存方法不是静态的,因此您必须更改

  when(NotificacaoRepository.save( added )).thenReturn(added);
Run Code Online (Sandbox Code Playgroud)

将对象用作:

when(notificacaoRepositoryMock.save( added )).thenReturn(added);
Run Code Online (Sandbox Code Playgroud)