当我什至不使用参数化测试时,为什么会出现 ParameterResolutionException?

MrF*_*man 4 java junit spring-test junit5

我想为我的 BookService 编写一个测试。这就是那个测试。我不知道为什么我总是收到以下错误:

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter 
[com.mrfisherman.library.service.domain.BookService bookService] in constructor 
[public com.mrfisherman.library.service.domain.BookServiceTest(com.mrfisherman.library.service.domain.BookService,
com.mrfisherman.library.persistence.repository.BookRepository)].
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我在这里不使用参数化测试。先感谢您!

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Server.class)
class BookServiceTest {

    private final BookService bookService;
    private final BookRepository bookRepository;

    public BookServiceTest(BookService bookService, BookRepository bookRepository) {
        this.bookService = bookService;
        this.bookRepository = bookRepository;
    }

    @Test
    void saveBook() {
        //given
        Book book = new Book();
        book.setTitle("Book 1");
        book.setPublishYear(1990);
        book.setType(BookFormat.REAL);
        book.setIsbn("1234567890");
        book.setDescription("Very good book");
        book.setNumberOfPages(190);
        book.setSummary("Very short summary");
        book.setCategories(Set.of(new Category("horror"), new Category("drama")));

        //when
        bookService.saveBook(book);

        //then
        Optional<Book> loaded = bookRepository.findById(book.getId());
        assertThat(loaded).isPresent();

    }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*nen 6

在 JUnit Jupiter 中,ParameterResolutionException每当测试类构造函数、生命周期方法(例如@BeforeEach)或测试方法声明无法由注册ParameterResolver扩展之一解析的参数时,就会抛出 a 。

因此,ParameterResolutionException即使您不使用方法,也可以抛出a @ParameterizedTest

使用时@SpringBootTest,系统SpringExtension会自动为您注册。它SpringExtension实现了ParameterResolverJUnit Jupiter 的扩展 API,以便您可以将 BeanApplicationContext注入到测试类中的构造函数和方法中。

解决问题的最简单方法是用 注释BookServiceTest构造函数@Autowired

有关更多信息和替代方法,请查看Spring 参考文档的依赖注入部分。SpringExtension