首页 > 解决方案 > 如何在 jupiter Spring Boot 中使用 any()?

问题描述

我正在尝试测试用于检索书籍的控制器方法。出于某种原因,我想用下面的 when() 方法模拟的 uploadBook() 不返回对象。

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

为了让 .when() 查看匹配项并返回一个对象模拟对象,我想使用 any(Object.class) 但它似乎在 Jupiter5 中不起作用,就像在 JUnit4 中一样

我想做类似下面的事情

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

但是,它要求我将 any() 转换为该方法请求的参数。当我这样做并执行时,它会引发一个强制转换异常。

谁能帮助并告诉我我做错了什么或我错过了什么?或者,如果您明白为什么我的 .when() 没有看到匹配项,那将不胜感激。

这是我试图模拟的方法

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

谢谢

标签: spring-bootjunit5spring-testspringmockito

解决方案


any(Class<T> type)是一个普通的模仿功能。
在编译时和运行时,它不能被 JUnit 破坏。因此,当您为测试类正确设置 Spring 单元测试配置时,
使用 JUnit4 或 JUnit 5 不应改变行为,该配置是 JUnit 4 中兼容的 Spring Runner 和 JUnit 5 中兼容的 Spring Extension。 此外,您的原始代码在mocking with在你的单元测试中设置了一些弱点。 关于您当前的问题,我敢打赌您在某处使用了错误的导入,可能是针对. 它应该是静态的;any()
any()
any()org.mockito.ArgumentMatchers.any


推荐阅读