Java 如何使用SpringBoot 2运行单元测试
我有以下测试:Java 如何使用SpringBoot 2运行单元测试,java,spring,spring-boot,junit,junit5,Java,Spring,Spring Boot,Junit,Junit5,我有以下测试: @SpringBootTest @ExtendWith(SpringExtension.class) class BookServiceImplTest { @MockBean private BookRepository bookRepository; @MockBean private LibraryService libraryService; @Autowired private BookServiceImpl bookS
@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),但我得到了一个关于bookserviceimplbean的异常,没有找到
我知道如何使用MockitoExtension和@Mock、@InjectMocks来实现这一点,但我想知道是否有一种更好的SpringBoot方式来实现这一点
@SpringBootTest
,这将加载整个上下文并降低测试速度。@MockBean
的作用是从指定的bean创建一个mock,并将其添加到上下文中。因为没有上下文运行,所以使用@MockBean
@RunWith(SpringRunner.class)
@Profile("test")
@Configuration
public class BookServiceTestConfiguration {
@Bean
public BookRepository bookRepository() {
return Mockito.mock(BookRepository.class);
}
@Bean
public LibraryService libraryService() {
return Mockito.mock(LibraryService.class);
}
@Bean
public BookService bookService() {
BookServiceImpl bookService = new BookServiceImpl(
bookRepository(), libraryService()
);
return userGroupService;
}
}
@ActiveProfiles("test")
@Import(BookServiceTestConfiguration .class)
@RunWith(SpringRunner.class)
public class BookServiceUnitTest {
@Autowired
private BookService bookService;
// write unit tests
}
您可以通过四个步骤进行单元测试:
- 删除
注释,因为它正在旋转整个Spring上下文―对于模拟所有协作者的单元测试不有用@SpringBootTest
- 从BookServiceImpl声明中删除
注释,并添加一个@Autowired
设置方法,在该方法中初始化@beforeach
并将bookService
和booksrepository
作为参数传递libraryService
- 在带注释的扩展中使用
而不是MockitoExtension
。在这里,我假设您能够使用类似的库来模拟您的合作者SpringExtension
- 使用Mockito的
而不是@Mock
,因为我们正在手动初始化@MockBean
,所以不需要处理springbeanbookService
在第一个问题上再补充一点:
@Mockbean
和@Autowired
是对集成测试有意义的注释,因为它们处理bean的模拟和注入。单元测试应该孤立地考虑这个类,嘲弄与其他类的交互,因此不需要旋转应用程序上下文并设置bean。< / P>我不认为您有这样的选项,也可以使用<代码> @ SpRunBooTest或“代码> @ CONTROXTIONTION/COMPUTE @ @ RunIn(SaveRunn.class)ˋ仅在没有本地JUnit 5支持时才需要。它将使用JUnit4来运行JUnit5测试。这里不需要。