【发布时间】:2020-04-07 04:34:47
【问题描述】:
我如何使用 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);
}
}
【问题讨论】:
-
通过编写测试。但是为什么要实现 100% 的分支覆盖率呢?
-
不要在 cmets 中发布您拥有的内容。编辑我们的问题。
-
请展示你的测试。又是一个问题:为什么要实现 100% 的分支覆盖率?我建议编写有价值的测试,例如行为测试。
-
您的代码无法编译。从修复它开始。然后意识到将断言放在 try 块中并不是您需要做的。您需要做的(如果您真的不希望 JUnit 5 支持异常测试)是将对您的方法的调用放在 try 块中。你的一些测试对我来说没有多大意义。我会建议,在编写代码之前,为您的测试编写一个文本描述,例如“从空堆栈中弹出一个元素应该引发异常,因为没有什么可以弹出”。为 testTC3 这样做可能会让你意识到自己的错误。
标签: java eclipse junit junit4 junit5