【问题标题】:How to mock a CrudRepository call?如何模拟 CrudRepository 调用?
【发布时间】:2015-04-16 05:00:02
【问题描述】:

我正在尝试对 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);

我的 TestContext 类有这个 bean

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

我的仓库就是这样

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

但它甚至没有编译,我不断收到“Cannot make a static reference to the non-static method save(Notificacao) from the type CrudRepository”最后一行“when(NotificacaoRepository.save( added ))

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

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

【问题讨论】:

    标签: java spring spring-mvc mocking mockito


    【解决方案1】:

    由于保存方法不是静态的,所以你必须改变

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

    将对象用作:

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

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 2021-04-26
      • 1970-01-01
      • 2012-07-26
      • 2019-05-19
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      相关资源
      最近更新 更多