JUnit 测试-assertTrue 不抛出异常
这是我的第一个 JUnit 测试,我不明白为什么没有抛出 AssertionError
,我做错了什么?
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
public class MyFirstJUnitTest {
public static void main(String[] args) {
JUnitCore.runClasses(MyFirstJUnitTest.class);
}
@Test
public void simpleAdd() {
int a = 5;
int b = 3;
int c = a + b; //8
Assert.assertTrue(c == 7);
}
}
This is my first JUnit test and I don't understand why is not throwing an AssertionError
, what am I doing wrong??
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
public class MyFirstJUnitTest {
public static void main(String[] args) {
JUnitCore.runClasses(MyFirstJUnitTest.class);
}
@Test
public void simpleAdd() {
int a = 5;
int b = 3;
int c = a + b; //8
Assert.assertTrue(c == 7);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要从命令行运行 JUnit,您需要调用主要方法。
除非您需要以编程方式访问结果,否则不应使用 JUnitCore,例如,如果您正在为 IDE 编写 JUnit 插件:
JUnitCore 捕获任何异常并将它们存储在
Result
中,这是 JUnit 插件将读取的类。To run JUnit from the command line you need to call the main method.
You are not supposed to use
JUnitCore
unless you need to access the result in a programmatic way, for instance if you are writing a JUnit plugin for an IDE:JUnitCore
catches any exceptions and stores them in theResult
, which is a class that your JUnit plugin will read.在这种情况下,
AssertionError
被测试运行程序捕获。通常,使用
assert
关键字进行的断言失败会引发AssertionError
。这:在启用断言检查的情况下运行时,会按预期抛出
AssertionError
。AssertionError
is in this case caught by test runner.Normally,
AssertionError
s are thrown by failing assertions made withassert
keyword. This:throws an
AssertionError
as expected, when running with assertion checks enabled.断言不是为了抛出异常,而是为了检查条件是否正确。因此,这将向您显示出现了问题(在 IDE 的 JUnit 视图中),但不会抛出任何异常。
Assertions are not for throwing exceptions but for checking if your condition is correct. So this will show you, that something went wrong (in your JUnit-view in your IDE) but not throw any exceptions.