SpingBoot2.x+Mockito+Junit5单元测试
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.初始化
3.编写单元测试类
准备两个类,HelloService、HelloMapper
@Service
public class HelloService {
@Autowired
private HelloMapper helloMapper;
public String hello() {
if (helloMapper != null) {
return helloMapper.sout();
}
return "";
}
}
@Repository
public interface HelloMapper {
default String sout() {
return "666";
}
}
-
单元测试类编写代码(有两种方式)
-
方式一: @ExtendWith(MockitoExtension.class)
public class Junit5Mockito {
@InjectMocks
private HelloService helloService;
@Mock
public HelloMapper helloMapper;
@Test
void testHelloService() {
when(helloMapper.sout()).thenReturn("777");
String hello = helloService.hello();
Assertions.assertEquals(hello, "777");
}
}
-
方式二: class HelloServiceTest {
@InjectMocks
private HelloService helloService;
@Mock
public HelloMapper helloMapper;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testHelloService() {
when(helloMapper.sout()).thenReturn("777");
String hello = helloService.hello();
Assertions.assertEquals(hello, "777");
}
4.其他 单元测试JUnit5使用:https://www.yuque.com/atguigu/springboot/ksndgx Junit5整合MockitoExtension扩展:https://javadoc.io/static/org.mockito/mockito-junit-jupiter/3.11.2/org/mockito/junit/jupiter/MockitoExtension.html Mockito官方文档:https://javadoc.io/static/org.mockito/mockito-core/3.1.0/org/mockito/Mockito.html#45 JUnit5官方文档:https://junit.org/junit5/docs/current/user-guide/ Springboot-testing官方文档:https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/html/spring-boot-features.html#boot-features-testing MockitoAnnotations-api:https://javadoc.io/static/org.mockitomockito-core/3.1.0/org/mockito/MockitoAnnotations.html Mockito官方文档中文翻译:https://blog.csdn.net/bboyfeiyu/article/details/52127551?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.control @Mock 和 @InjectMocks组合使用:https://www.jianshu.com/p/bb705a56f620 ?
|