public class test1 { static String result; public static String test1(String username,String password) { if(username==""&&password=="") { result = "用户名或密码不能为空"; } else if(username=="admin"&&password=="123") { result = "登录成功"; } else if(username!="admin"&&password=="123") { result = "请输入正确的用户名"; } else if(username=="admin"&&password!="123") { result = "请输入正确的密码"; } else if(username!="admin"&&password!="123") { result = "请输入正确的用户名和密码"; } return result;测试类中设计最少的测试数据满足语句覆盖测试,测试类使用参数化测试(@Parameters)完成测试。使用assertEquals判断输入数据测试方法期望结果值和实际返回值是否一致。
时间: 2023-11-11 11:50:35 浏览: 74
你可以使用参数化测试来测试`test1`方法的不同输入情况。这样可以减少测试代码的重复,并提供更好的可读性和维护性。下面是一个使用JUnit的参数化测试的示例代码:
```java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class test1Test {
private final String username;
private final String password;
private final String expected;
public test1Test(String username, String password, String expected) {
this.username = username;
this.password = password;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection<Object[]> testData() {
return Arrays.asList(new Object[][]{
{"", "", "用户名或密码不能为空"},
{"admin", "123", "登录成功"},
{"guest", "123", "请输入正确的用户名"},
{"admin", "456", "请输入正确的密码"},
{"guest", "456", "请输入正确的用户名和密码"}
});
}
@Test
public void testLogin() {
String result = test1.test1(username, password);
Assert.assertEquals(expected, result);
}
}
```
在这个测试类中,我们使用了`@RunWith(Parameterized.class)`注解来指定使用参数化测试的运行器。然后,我们定义了一个`testData`方法,返回一个包含不同测试数据的集合。每个测试数据包含用户名、密码和预期结果。在`testLogin`方法中,我们通过调用`test1`类的`test1`方法,并使用`Assert.assertEquals`来断言实际结果与预期结果是否一致。
通过这种方式,你可以通过添加更多的测试数据来增加测试覆盖率,确保代码的可靠性。