如何为一个测试方法运行多个测试用例
我正在使用 JUnit。我有一个测试方法来测试方法和一些测试用例。我想运行该测试方法中的所有 tes 案例,但我不能这样做。当第一个测试用例失败时,测试方法不运行第二个测试用例
这是我的代码
public class ComputeServiceTest extends TestCase {
//test add method
public void testAdd()
{
ComputeServices instance = new ComputeServices();
//First test case
int x1 = 7;
int y1 = 5;
int expResult1 = 13;
int result1 = instance.add(x1, y1);
assertEquals("First test case fail",expResult1, result1);
// Second test case
int x2 = 9;
int y2 = 6;
int expResult2 = 15;
int result2 = instance.add(x2, y2);
assertEquals("Second test case fail",expResult2, result2);
}
我该怎么做?
I'm using JUnit.I have a test method to test a method and some test cases. I want to run all tes case in that test method, but I can't do that. When first test case fail, test method don't run second test case
Here is my code
public class ComputeServiceTest extends TestCase {
//test add method
public void testAdd()
{
ComputeServices instance = new ComputeServices();
//First test case
int x1 = 7;
int y1 = 5;
int expResult1 = 13;
int result1 = instance.add(x1, y1);
assertEquals("First test case fail",expResult1, result1);
// Second test case
int x2 = 9;
int y2 = 6;
int expResult2 = 15;
int result2 = instance.add(x2, y2);
assertEquals("Second test case fail",expResult2, result2);
}
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
测试用例在第一次断言失败时中止,这是设计使然。
这是为了隔离测试用例:如果您的第二个断言失败,您如何知道 instance.add(9, 6) 是否被破坏,或者这是否是由第一次调用 add() 方法引起的?
当被测试的方法返回一个对象时,或者在发生错误时返回 NULL 时,这很有用。第一个断言确保该方法返回一个对象,然后可以调用该对象的方法来验证其状态。当返回 NULL 时,测试用例在第一个断言上中止,不会抛出 NullPointerException (该模式名为 守卫断言)。
一个测试用例中可以有尽可能多的测试方法。
A test case aborts at the first assertion failure, this is by design.
This is to isolate the test cases: if your second assertion fails, how would you know if instance.add(9, 6) is broken, or if this has been caused by the first invocation of the add() method ?
This is useful when the method under test returns an object, or NULL in case of an error. The first assertion ensures the method returned an object, and then it is possible to invoke methods of that object to verify its state. When NULL is returned, the test case aborts on the first assertion an no NullPointerException will be thrown (the pattern is named guard assertion).
It is possible to have as many test methods in a TestCase.
这里的标准建议是将第二个测试用例放入一个单独的方法中,然后无论第一个“测试用例”是否成功,它都会运行。
您可以使用 setUp 方法来初始化 ComputeServices 实例,这样您就不需要在每个测试方法中使用该样板文件。
The standard advice here would be to put your second test case into a separate method, then it will run regardless of whether or not the first "test case" succeeds or not.
You can use a setUp method to initialize the ComputeServices instance so you don't need that boilerplate in each test method.