Java (j) 单元测试断言和错误消息?
我目前正在测试一个方法,让我称之为Java (j) 单元测试断言和错误消息?,java,unit-testing,junit,assert,Java,Unit Testing,Junit,Assert,我目前正在测试一个方法,让我称之为testedMethod() 方法的主体如下所示 private testedMethod(List<Protocoll> protocolList) { //so something with the protocolList if (something) && (somethingElse) { Assert.isFalse(areTheProtocollsCorrect(p1, p2), "Err
testedMethod()
方法的主体如下所示
private testedMethod(List<Protocoll> protocolList) {
//so something with the protocolList
if (something) && (somethingElse) {
Assert.isFalse(areTheProtocollsCorrect(p1, p2), "Error, the protocols are wrong");
}
if (somethingCompeletlyElse) && (somethingElse) {
Assert.isFalse(areTheProtocollsExactlyTheSame(p1, p2), "Error, the protocols are the same");
}
}
伊斯特鲁:
public static void isTrue(boolean condition, String descr) {
if (!condition) {
fail(descr);
}
}
失败:
测试该方法应该正确执行的操作已经完成。但我想测试一下这些断言。这个断言是代码的一个重要部分,我想看看当我向该方法提供错误数据时,该方法是否抛出了这些错误。我如何使用JUnit呢?首先,如果您当前正在使用JUnit,您不应该编写自己的
assert*
或fail
方法:它们已经包含在类中
无论如何,如果要测试断言,必须编写两种测试用例:肯定用例和否定(失败)用例:
@测试
公开无效的正片1()
{
//用您知道必须工作的数据填充输入参数:
列表原碰撞=。。。
测试方法(原碰撞);
}
@试验
公开无效的正片2()
{
...
}
@测试(预期=AssertException.class)
公共无效否定1()
{
//用您知道不能工作的数据填充输入参数:
列表原碰撞=。。。
测试方法(原碰撞);
}
@测试(预期=AssertException.class)
公共无效否定条款2()
{
...
}
Test
注释中的expected
参数使JUnit检查是否引发了该类型的异常。否则,测试将被标记为失败
但是我仍然坚持使用JUnit标准更好。您的代码中有JUnit
Assert
?是弹簧断言?如果是Spring,请检查是否存在IAE
s。断言.isFalse()的作用是什么?如果这是你自己的代码,你应该把它包括在问题中。@kryger@Dave Newton-我已经从Assert.class
中添加了方法,所以请检查异常。我想我不明白问题是什么。谢谢你的回答,不过,我还是在使用JUnit断言。我代码中的其他断言有完全不同的用途,它们不用于JUnit测试:)OK。那样的话,我的回答适合你的情况。
public static void isTrue(boolean condition, String descr) {
if (!condition) {
fail(descr);
}
}
public static void fail(String descr) {
LOGGER.fatal("Assertion failed: " + descr);
throw new AssertException(descr);
}
@Test
public void positiveCase1()
{
// Fill your input parameters with data that you know must work:
List<Protocoll> protocolList=...
testedMethod(protocolList);
}
@Test
public void positiveCase2()
{
...
}
@Test(expected=AssertException.class)
public void negativeCase1()
{
// Fill your input parameters with data that you know must NOT work:
List<Protocoll> protocolList=...
testedMethod(protocolList);
}
@Test(expected=AssertException.class)
public void negativeCase2()
{
...
}