JUnit测试用例的一些用法

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!");
    }
}

注意事项

  1. junit的测试方法必须使用@Test注解
  2. 测试方法必须以public void修饰,并且不包含参数
  3. 测试代码的包应该和被测试代码包结构保持一致
  4. 测试单元中的每个方法必须可以独立测试,方法间不能有任何依赖
  5. 测试类一般使用Test作为类名的后缀
  6. 测试方法使一般用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");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值