java - 如何模拟 CrudRepository 调用?

标签 java spring spring-mvc mocking mockito

我正在尝试对 Spring MVC 应用程序进行简单的 Controller 测试

我有这个测试类

@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);

我的 TestContext 类有这个 bean

@Bean
public NotificacaoRepository todoService() {
    return Mockito.mock(NotificacaoRepository.class);
}

我的仓库就是这样

public interface NotificacaoRepository extends CrudRepository<Notificacao, Long> {
}

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

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

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

最佳答案

因为保存方法不是静态的,你将不得不改变

  when(NotificacaoRepository.save( added )).thenReturn(added);

将对象用作:

when(notificacaoRepositoryMock.save( added )).thenReturn(added);

关于java - 如何模拟 CrudRepository 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29665668/

相关文章:

java - Spring 覆盖 bean 配置设置其 "Primary"一个

java - Spring 数据(其余): Date serialization mapping returns a wrong value

java - Spring Security + CAS SSO 身份验证管理器

java - Spring MVC 是否缓存在 Web 应用程序启动时未加载的 bean 文件?

java - 将行参数从 ant 传递给 main

java - 在 Spring 中使用 SimpleJdbcCall 调用返回行的 Oracle 过程

java - 使用Java查找行中的重复值

java - 将 html 代码作为属性添加到 ModelAndView 中

java - Spring boot 2.0.2,使用Aop拦截Cloud Stream注释不再起作用

java - Bean 从 Controller 到另一个 Controller