1、常见问题
当类名定义为Test时,这时在用注释@Test会提示type mismatch:cannot convert from Test to Annotation 类型不匹配:无法将Test转换为注释,此时将类Test换成其他名字就可以了。
//The import org.junit.Test conflicts with a type defined in the same file
//导入org.junit.Test 与同一文件中定义的类型冲突
import org.junit.Test;
public class Test{
//type mismatch:cannot convert from Test to Annotation
//类型不匹配:无法将Test转换为注释
@Test
public void test(){
System.out.println("Hello World!");
}
}
注意事项
- junit的测试方法必须使用@Test注解
- 测试方法必须以public void修饰,并且不包含参数
- 测试代码的包应该和被测试代码包结构保持一致
- 测试单元中的每个方法必须可以独立测试,方法间不能有任何依赖
- 测试类一般使用Test作为类名的后缀
- 测试方法使一般用test作为方法名的前缀
2、常用的注解
1.@BeforeClass – 表示在类中的任意public static void方法执行之前执行
2.@AfterClass – 表示在类中的任意public static void方法执行之后执行
3.@Before – 表示在任意使用@Test注解标注的public void方法执行之前执行
4.@After – 表示在任意使用@Test注解标注的public void方法执行之后执行
5.@Test – 使用该注解标注的public void方法会表示为一个测试方法
一个JUnit4 的单元测试用例执行顺序为:
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一个测试方法的调用顺序为:
@Before –> @Test –> @After
3、Response的创建
String path = “nrcs/data”;
Response response = fileProviderClient.download(path);
测试方法
byte[] bytes = new byte[]{“1”};
Map<String,Collection<String>> headers = new HashMap<>();
Response resp = Response.builder().body(bytes).status(200).reason(“1”).headers(headers).build();
Mockito.when(fileProviderClient.download(Mokito.any())).thenReturn(resp)
4、同一个方法不同参数类型
EsbUtil.getBaseRequest(Mockito.any(),Mockito.any(A.class)).thenReturn(any);
通过再Mockito.any()的参数中确定泛型的类型
5、同一个方法中有两此方法调用,要返回不同的结果
通过第一个参数是第一次调用返回的结果,第二个参数是第二次调用返回的结果Mockito.when(imageService.getFileBarCode(Mockito.any)).thenReturn(“1”,“2”)
6、涉及静态方法
@PrepareForTest({PosUtils.class})
PowerMockito.mockStatic(PosUtils.class);//不写会报错
Mockito.when(PosUtils.getNowDate()).thenReturn(“20211027”)
7、集合问题
如果测试方式涉及到循环,列表循环之后数据会记录内存中
8、反射工具类 ReflectionTestUtils
代码中有用@Value注解从yml中引入的变量,这个时候可以用反射来赋值
ReflectionTestUtils.setField(类名,参数名,参数赋值);
package com.springtest;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* 使用ReflectionTestUtils解决依赖注入
*/
public class ReflectionTestUtilsTest {
@Test
public void testDefault(){
//@InjectMocks
//private Foo tFoo
Foo tFoo = new Foo();
//set private property
ReflectionTestUtils.setField(tFoo, "m_String", "Hello");
//invoke construct and destroy method
ReflectionTestUtils.invokeMethod(tFoo, "onStarted");
ReflectionTestUtils.invokeMethod(tFoo, "onStop");
}
}