spring-bootjunit5spring-testspringmockito

How to use any() in jupiter Spring Boot?


I am trying to test a controller method for retrieving a book. For some reason the uploadBook() that I want to mock with when() method below doesn't return an object.

@Test
    void uploadNewBookTest() {
        MockMultipartFile firstFile = new MockMultipartFile("book", "filename.txt", "text/plain", "some xml".getBytes());
        Author author = new Author("John", "Doe", "john.doe@mail.ru");
        BookDto bookDto = new BookDto("some title", "desc", "en-US", "Sci-Fi", "pdf", "2020-12-10", author.getEmail(), "sdd23421");
        
        Mockito.when(bookUploadService.uploadBook(bookDto, firstFile))
            .thenReturn(Optional.of(bookDto));
        
        try {
            mockMvc.perform(
                    MockMvcRequestBuilders.multipart("/books")
                    .file(firstFile)
                    .param("title", bookDto.getTitle())
                    .param("shortDescription", "asdf")
                    .param("publishedDate", bookDto.getPublishedDate())
                    .param("language", bookDto.getLanguage())
                    .param("genre", bookDto.getGenre())
                    .param("email", "hell")
                    )
            .andExpect(status().isOk());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

For the .when() to see a match and return a object mocked object, I want to use the any(Object.class) but it seems it doesn't work in Jupiter5 the same way it works in JUnit4

I would like to do something like below

Mockito.when(bookUploadService.uploadBook(any(BookDto.class), any(MultipartFile.class)))
    .thenReturn(Optional.of(bookDto));

However, It asks me to cast the any() to the param requested by the method. When I do and execute, it throws an cast exception.

Can anyone help and tell me what I do wrong or what I am missing ? Or if you see why my .when() doesn't see a match, that will be highly appreciated.

Here is the method I am trying to mock

public Optional<BookDto> uploadBook(BookDto bookDto, MultipartFile bookFile)

Thanks


Solution

  • any(Class<T> type) is a plain mockito feature.
    At compile time as well as at runtime, it cannot be mangled by JUnit.
    So using JUnit4 or JUnit 5 should not change the any() behavior while you set correctly the Spring unit test configuration for your test class that is a compatible Spring Runner in JUnit 4 and a compatible Spring Extension in JUnit 5.
    Besides, your original code is valid while mocking with any() sets a some weakness in your unit test.
    About your current issue, I bet that you use a wrong import somewhere, probably for any(). It should be static org.mockito.ArgumentMatchers.any;