简体   繁体   English

如何为一种测试方法运行许多测试用例

[英]How can I run many test cases for a test method

I'm using JUnit.I have a test method to test a method and some test cases. 我正在使用JUnit。我有一个测试方法来测试一个方法和一些测试用例。 I want to run all tes case in that test method, but I can't do that. 我想在该测试方法中运行所有tes案例,但是我不能这样做。 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? 我怎样才能做到这一点?

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. 您可以使用setUp方法来初始化ComputeServices实例,因此您无需在每个测试方法中都使用该样板。

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 ? 这是为了隔离测试用例:如果您的第二个断言失败,您如何知道instance.add(9,6)是否损坏,或者这是由第一次调用add()方法引起的?

This is useful when the method under test returns an object, or NULL in case of an error. 当被测方法返回一个对象时,或当错误时为NULL时,此功能很有用。 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 ). 当返回NULL时,测试用例在第一个断言时中止,并且不会引发NullPointerException(该模式称为Guard assertion )。

It is possible to have as many test methods in a TestCase. 一个TestCase中可以有尽可能多的测试方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM