如何使用java和@test注释使用junit测试用例实现该类中的3种方法的完整分支覆盖。
public class StringStack {
private int capacity = 10;
private int pointer = 0;
private String[] objects = new String[capacity];
public void push(String o) {
if (pointer >= capacity)
throw new IllegalArgumentException("Stack exceeded capacity!");
objects[pointer++] = o;
}
public String pop() {
if (pointer <= 0)
throw new IllegalArgumentException("Stack empty");
return objects[--pointer];
}
public boolean isEmpty() {
return pointer <= 0;
}我已经为isEmpty()方法编写了以下测试cases,虽然我很难为另外两种方法编写测试用例,因为它们都返回对象指针,而且我不知道如何在测试文件中初始化它们。
class squareTest {
//1.
@Test
public void push() {
StringStack push1 = new StringStack();
String e2 = push1.pop();
try {
Assert.fail( "Should have thrown an exception" );
assertEquals(IllegalArgumentException("Stack empty"), e2);
//java.lang.IllegalArgumentException: Stack empty
}catch (Exception e) {
String expmessage = "I should get this message";
}
}
@Test
public void testTC3()
{
try {
StringStack.push(o);
fail(); // if we got here, no exception was thrown, which is bad
}
catch (Exception e) {
final String expected = "Legal Values: Package Type must be P or R";
assertEquals( expected, e.getMessage());
}
}
//3.EMPTY TEST CASES
@Test
public void empty()
{
StringStack test2 = new StringStack();
boolean e1 = test2.isEmpty();
assertEquals(true, e1);
}
@Test
public void notEmpty()
{
StringStack test3 = new StringStack();
boolean ne1 = test3.equals("im not empty");
assertEquals(false, ne1);
}
}发布于 2019-12-15 04:44:56
也许下面的测试,同时帮助获得全面的覆盖。
推法试验
@Test(exception = IllegalArgumentException.class)公共IllegalArgumentException.class WhiteBox.setInternalState(yourObject,“指针”,11);String inputString = "Hello";yourObject.push(inputString);}
@Test public void push_PointerSmallerThanCapacity_ExceptionThrow(){ inputString = "Hello";yourObject.push(inputString);int指针= WhiteBox.getInternalState(yourObject,“指针”);String[] objects = WhiteBox.getInternalState(yourObject,"objects");assertEquals(inputString,objectspin-1);}
pop法试验
@Test(exception = IllegalArgumentException.class)公共pop_PointerNegative_ExceptionThrow(){ WhiteBox.setInternalState(yourObject,“指针”,-1);字符串inputString = "Hello";yourObject.push(inputString);}
@Test void pop_pointerGreaterThenZero_PopValue(){ //set指针WhiteBox.setInternalState(yourObject,“指针”,2);String[] stringList = {"String0“、"String1”、"String2"};//对象数组WhiteBox.setInternalState(yourObject,"objects",stringList);String actualOutput = yourObject.pop();assertEquals(actualOutput,stringList1);}
在这里,yourObject是您测试的类的对象。
发布于 2019-12-13 17:41:03
我将给出第一个函数的例子。
public void push(String o) {
if (pointer >= capacity)
throw new IllegalArgumentException("Stack exceeded capacity!");
objects[pointer++] = o;
}您需要3次统一测试才能完全涵盖这一项。
指针
的最后一个
对于分支覆盖,您只需要1和3或2和3,虽然我建议这三种功能的关键部分。
https://stackoverflow.com/questions/59327388
复制相似问题