我最近尝试过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]'>
....
除了yesDataPoint @DataPoint导致失败之外,有没有办法摆脱那些对* 我的 *测试一无所知的24条第一行?这是我需要的信息,知道什么是失败的,但我真的想知道 它在同一时间失败。
[编辑]
我用经典的org.junit.Assert.assertEquals替换了org.fest.assertions的用法,以避免混淆。 此外,它与Eclipse无关:当您从命令行运行并使@Theory失败时,您也可以获得长(无用/混乱)堆栈跟踪。
答案 0 :(得分:0)
抓住ComparisonFailure并打印它的GetMessage()是否有问题?
public void sayNo(final String say) {
try {
assertThat(say).isEqualTo("no");
}catch(ComparisonFailure e) {
System.out.println(e.getMessage);
}
}
道歉,如果有什么我误解的话。
编辑:ComparisonFailure还有getExpected()和getActual()方法,如果您正在寻找某种格式,可以调用它们。
答案 1 :(得分: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。