Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a CrudRepository call?

I am trying to make a simple controller test on a Spring MVC application

I have this test class

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

my TestContext class has this bean

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

and my repository is just that

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

but it didn't even compile, I keep getting "Cannot make a static reference to the non-static method save(Notificacao) from the type CrudRepository" on the last line "when(NotificacaoRepository.save( added ))"

I saw this kind of use on an example in this link http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/ but there he uses a service class and it is not exactly like the use of CrudRepository.

I tried to find an example of how to test a CrudRepository implementation but didn't find one, so I am thinking this should be simple like others mocks

like image 677
danielbchaves Avatar asked Nov 01 '22 06:11

danielbchaves


1 Answers

Since the save method is not static, you will have to change

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

To use an object as:

when(notificacaoRepositoryMock.save( added )).thenReturn(added);
like image 111
Phoenix Avatar answered Nov 09 '22 10:11

Phoenix