[英]JUnit 5 testing
我如何使用 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() 方法實現了這一點,盡管我正在努力為其他兩種方法編寫測試用例,因為它們都返回對象指針,而我不知道如何在我的測試文件中對其進行初始化.
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);
}
}
我會給你一個第一個函數的例子
public void push(String o) {
if (pointer >= capacity)
throw new IllegalArgumentException("Stack exceeded capacity!");
objects[pointer++] = o;
}
你需要 3 個統一測試來完全覆蓋這個
對於分支覆蓋,您只需要 1 和 3 或 2 和 3,盡管我建議所有三個都用於關鍵功能。
也許低於測試同時有助於獲得全面覆蓋。
推法測試
指針 >= 容量
@Test(exception = IllegalArgumentException.class) public void push_PointerGreaterThanCapacity_ExceptionThrow(){ WhiteBox.setInternalState(yourObject, "pointer",11); String inputString = "Hello"; yourObject.push(inputString); }
指針<容量
@Test public void push_PointerSmallerThanCapacity_ExceptionThrow(){ String inputString = "Hello"; yourObject.push(inputString); int pointer = WhiteBox.getInternalState(yourObject,"pointer"); String[] objects = WhiteBox.getInternalState(yourObject,"objects"); assertEquals(inputString, objects[pointer-1]); }
流行方法測試
指針 < 0
@Test(exception = IllegalArgumentException.class) public void pop_PointerNegative_ExceptionThrow(){ WhiteBox.setInternalState(yourObject, "pointer",-1); String inputString = "Hello"; yourObject.push(inputString); }
指針 > 0
@Test public void pop_pointerGreaterThenZero_PopValue(){ //set pointer WhiteBox.setInternalState(yourObject, "pointer",2); String[] stringList = {"String0","String1","String2"}; //object array WhiteBox.setInternalState(yourObject, "objects",stringList); String actualOutput = yourObject.pop(); assertEquals(actualOutput, stringList[1]); }
在這里, yourObject 是您測試的類的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.