采用Junit写测试代码,assertEquals()方法对StringOperator类的方法完成单元测试,测试过程中如果出错,说明期待值、真实值和出错原因。
时间: 2023-05-27 14:04:34 浏览: 61
示例代码:
```java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringOperatorTest {
@Test
public void testConcat() {
StringOperator operator = new StringOperator();
String result = operator.concat("hello", "world");
assertEquals("helloworld", result);
}
@Test
public void testSubstring() {
StringOperator operator = new StringOperator();
String result = operator.substring("hello world", 1, 4);
assertEquals("ell", result);
}
}
```
这里我们对StringOperator类的concat()和substring()方法进行单元测试。
在testConcat()方法中,我们创建了一个StringOperator对象,调用concat()方法并传入参数"hello"和"world",期望返回值为"helloworld"。使用assertEquals()方法来比较期待值和真实值是否相等,如果不相等,则会抛出AssertionError并且提示出错原因。
在testSubstring()方法中,同样创建了一个StringOperator对象,调用substring()方法并传入参数"hello world"、1和4。期待返回值为"ell"。同样使用assertEquals()方法进行比较。
如果程序出现错误,我们可以根据错误提示来分析出错原因,从而进行修复。