topic
class under test
public class java4 {
public String data(String x) {
//判断x是否以字母开头,位数在2位以上
//" ^ "是已什么开头,写法:”^[a-z]“意思是以a-z开头
//”{2,}“意思是两位以上字符
//”{0,9}“意思是9位字符以内
if (x.matches("(^[a-z][a-zA-Z]{2,})$")){
//x是否以ab开头
if (x.startsWith("ab")){
//将ab开头改为ef开头
System.out.println(x.replaceFirst("ab", "ef"));
return x.replaceFirst("ab", "ef");
}
//x不以ab开头,以cd结尾
else if (!x.startsWith("ab")&&x.endsWith("cd")) {
//将所有cd变换为gh
System.out.println(x.replace("cd", "gh"));
return x.replace("cd", "gh");
}else {
//将所有字母转换为大写
System.out.println(x.toUpperCase());
return x.toUpperCase();
}
}
else {
return null;
}
}
}
Test class parameterization settings
Declare variables, test data, and expected outcome variable declarations, including special runners specified by the test class
@RunWith(Parameterized.class)
public class java4Test {
java4 aa=new java4();
String x;
String y;
public constructor
public java4Test(String x,String y) {
this.x=x;//输入数据
this.y=y;//断言数据
}
A public static method annotated with @Parameters and contains data that needs to be tested for initialization
@Parameters
public static Collection<Object[]>data() {
return Arrays.asList(new Object[][]{
//输入数据 //断言数据
{"absesde","efsesde"},
{"sdfcdcdcd","sdfghghgh"},
{"sfdesfe","SFDESFE"}
});
}
Test method, including assertions
@Test
public void test() {
String ss=aa.data(x);
assertEquals(y, ss);
}
complete test code
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
//声明变量,测试数据和期望结果变量声明,包括测试类指定的特殊运行器部分代码
@RunWith(Parameterized.class)
public class java4Test {
java4 aa=new java4();
String x;
String y;
//公共的构造函数部分
public java4Test(String x,String y) {
this.x=x;//输入数据
this.y=y;//断言数据
}
//@Parameters注释的公共静态方法,并且包含初始化需要测试的数据
@Parameters
public static Collection<Object[]>data() {
return Arrays.asList(new Object[][]{
{"absesde","efsesde"},
{"sdfcdcdcd","sdfghghgh"},
{"sfdesfe","SFDESFE"}
});
}
@Test
public void test() {
String ss=aa.data(x);
assertEquals(y, ss);
}
}
operation result