文章目录
1、插件安装
可以借助两种插件 squaretest
或者 TestMe
安装过程参考 Idea 单元测试插件的安装
2、Mockito 使用技巧
2.1、准备
MAVEN
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
测试类上的注解
@RunWith(MockitoJUnitRunner.class)
需运行内部逻辑对象的Mock
此对象会被 Mockito 实例化,无需Spring注入
不需要对这个对象的方法when,会实际执行内部逻辑
@InjectMocks
private Aaa aaa;
无需运行内部逻辑对象的Mock
此对象会被 Mockito 实例化,且不会运行内部的逻辑,但是需要指定对应参数下的返回结果,见2.2
@Mock
private Aaa aaa;
让注解生效
@Before
public void setup(){
//MockitoAnnotations.initMocks(this); //这个已过期
MockitoAnnotations.openMocks(this);
}
2.2、方法内
Mock 注入到一个变量
@Before
public void setup(){
ReflectionTestUtils.setField(对象, "fieldName", 值);
}
Mock方法任意入参都返回特定结果
when(aaa.method1(org.mockito.ArgumentMatchers.anyString()
, org.mockito.ArgumentMatchers.any()(),
org.mockito.ArgumentMatchers.any(AAA.class)))
.thenReturn(
java.util.Optional.of(new Demo("ddd"
, "",1,"")));
Mock方法指定入参返回特定结果
final Demoaaa demoaaa = new Demoaaa();
when(aaa.method1(new Demo("aaa"
, Arrays.asList("bbb")
, "ccc", 0L, "ddd")))
.thenReturn(demoaaa);
Mock 静态方法
使用 try 声明 Mock 资源,可以完成静态资源的自动回收(不回收会影响其它单测)
try(MockedStatic<BeanUtils> beanUtil = mockStatic(BeanUtils.class)){
beanUtil.when((MockedStatic.Verification) BeanUtils.getBean(Demo.class))
.thenReturn(demo);
// Run the test
demoTest.demoMethod(request);
}
Mock 静态方法完整案例
import demo.BeanUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.mockStatic;
@RunWith(MockitoJUnitRunner.class)
public class DemoImplTest {
@InjectMocks
private DemoImpl demoUnderTest;
@Mock
DemoA demoA;
@Before
public void setup(){
MockitoAnnotations.openMocks(this);
}
@Test
public void testDemoMethod() {
// Setup
final DemoRequest request = new DemoRequest();
request.setId(0L);
try(MockedStatic<BeanUtils> beanUtil = mockStatic(BeanUtils.class)){
beanUtil.when((MockedStatic.Verification) BeanUtils.getBean(DemoA.class))
.thenReturn(demoA);
// Run the test
final DemoResponse result = demoUnderTest.demoMethod(request);
}
}
}
2.3、结果判定
判定一致
// Verify the results
String result = aaa.method3();
assertThat(result).isEqualTo("ok");
assertThat(result).isEqualTo("ok");