2

我最近尝试了 Junit @Theory 测试风格:这是一种非常有效的测试方式。但是,我对测试失败时引发的异常不满意。例子 :

import static org.junit.Assert.assertEquals;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;


@RunWith(Theories.class)
public class TheoryAndExceptionTest {

    @DataPoint
    public static String yesDataPoint = "yes";

    @Theory
    public void sayNo(final String say) {
        assertEquals("no",say);
    }
}

我希望这个测试抛出一个描述性异常,而不是得到类似的东西:

org.junit.ComparisonFailure: expected:<'[no]'> but was:<'[yes]'>

...我明白了:

org.junit.experimental.theories.internal.ParameterizedAssertionError: sayNo(yes) at
....
[23 lines  of useless stack trace cut]
...
Caused by: org.junit.ComparisonFailure: expected:<'[no]'> but was:<'[yes]'>
....

有没有办法摆脱前 24 行,除了 yesDataPoint @DataPoint 导致失败之外什么都不告诉 * my *test ?这是我需要的信息,以了解失败的原因,但我真的很想知道它是如何同时失败的。

[编辑]

我用经典的 org.junit.Assert.assertEquals 替换了 org.fest.assertions 的用法,以避免混淆。此外,它也与 Eclipse 无关:当您从命令行运行 @Theory 并使其失败时,您也会得到那个长(无用/令人困惑的)堆栈跟踪。

4

2 回答 2

0

捕获比较失败并打印它的 GetMessage()是否有问题?

public void sayNo(final String say) {
    try {
        assertThat(say).isEqualTo("no");
    }catch(ComparisonFailure e) {
        System.out.println(e.getMessage);
    }
}

抱歉,如果我有什么误解。

编辑:ComparisonFailure 还具有 getExpected() 和 getActual() 方法,如果您正在寻找某些格式,您可以调用它们。

于 2012-12-06T20:37:17.530 回答
0

你有一个非常奇怪的图书馆。assertThat 的语法很奇怪。我建议:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.experimental.theories.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

@RunWith(Theories.class)
public class TheoryAndExceptionTest {

    @DataPoint
    public static String yesDataPoint = "yes";

    @Theory
    public void sayNo(final String say) {

        assertThat(say,is("no"));
    }

    @Test
    public void yesNo() {
        assertEquals("must be equal, ", "yes","no");
    }
}

然后你将拥有:

org.junit.experimental.theories.internal.ParameterizedAssertionError: sayNo(yesDataPoint)
....

Caused by: java.lang.AssertionError: 
Expected: is "no"
     got: "yes"

至于 assertEqual 你是对的,它似乎对理论没有帮助。仅适用于@Test:

    org.junit.ComparisonFailure: must be equal,  expected:<[yes]> but was:<[no]>

增加项:

你也可以使用

assertThat("must be equal, ", say,is("no"));

比你有输出:

Caused by: java.lang.AssertionError: must be equal, 
Expected: is "no"
     got: "yes"

至于过滤多余的行,请使用 Eclipse 中的 Failure Trace View。

于 2012-12-06T20:40:59.253 回答