总共2步
第一步,添加依赖
org.junit.jupiter
junit-jupiter-params
5.2.0
test
第二步,编写用例
主要使用@ParameterizedTest 和@ValueSource两个注解
import org.junit.
Test
;
import org.junit.jupiter.params.
ParameterizedTest
;
import org.junit.jupiter.params.provider.
ValueSource
;
import org.junit.runner.
RunWith
;
import org.springframework.test.context.junit4.SpringRunner
;
@RunWith(SpringRunner.
class)
public
class SomeServiceTest {
@ParameterizedTest
@ValueSource(ints = {
1
,
2
,
3})
public
void
testInt(
int num) {
System.
out.println(num)
;
}
@ParameterizedTest
@ValueSource(strings = {
“a”
,
“b”
,
“c”})
public
void
testStr(String str)
throws Exception {
System.
out.println(str)
;
}
@Test
public void
testOther() {
}
}
常见问题及解决办法
- java.lang.Exception: No runnable methods
如果测试类使用@RunWith(SpringRunner.class),则该类需要有至少一个无参测试方法,如上例中的testOther()方法 - 校验不通过的坑
Mockito.verify(abc,Mockito.atLeastOnce()).doSomething(Mockito.anyString()),但是具体方法调用的时候入参是null,那这个校验不通过,大概是因为null不能用任意字符串表示