【发布时间】:2020-07-28 22:35:55
【问题描述】:
我有以下测试:
@SpringBootTest
@ExtendWith(SpringExtension.class)
class BookServiceImplTest {
@MockBean
private BookRepository bookRepository;
@MockBean
private LibraryService libraryService;
@Autowired
private BookServiceImpl bookService;
@Test
void create() {
BookRequestDTO bookRequestDTO = new BookRequestDTO();
Library library = new Library();
Book expectedBook = new Book();
when(libraryService.getById(bookRequestDTO.getLibraryId()))
.thenReturn(library);
when(bookRepository.save(any(Book.class)))
.thenReturn(expectedBook);
Book actualBook = bookService.create(bookRequestDTO);
assertEquals(expectedBook, actualBook);
}
}
没关系,它可以运行,但我想知道有没有办法将它作为单元测试而不是集成测试运行,并且仍然使用@MockBean @Autowired。还是我遗漏了什么?
我尝试只留下 @ExtendWith(SpringExtension.class),但我得到一个关于未找到 BookServiceImpl bean 的异常。
我知道如何使用 MockitoExtension 和 @Mock、@InjectMocks 来做到这一点,但我想知道是否有更多的 SpringBoot 方式来做到这一点?
【问题讨论】:
-
我认为您没有这样的可选选项,请使用
@SpringBootTest或@ContextConfiguration
标签: java spring spring-boot junit junit5