在Junit 4中构建测试套件

时间:2013-10-09 19:16:31

标签: java unit-testing junit test-suite

现在,我有这个简单的测试套件:

@RunWith(Suite.class)
@Suite.SuiteClasses({
    CommentingTest.class,
    SubscriptionsTest.class,
    EditingTest.class,
    BasicOperationsTest.class
})
public class WebTestSuite { }

但是现在我想将参数传递给这些测试类,告诉他们是否要使用管理员帐户进行测试,是否要在视图模式A或B中进行测试等等。我希望我能做类似的事情这样:

@RunWith(Suite.class)
public class WebTestSuite {
    public WebTestSuite() {
        this.addTest(new CommentingTest(Accounts.ADMIN, ViewMode.A));
        this.addTest(new CommentingTest(Accounts.ADMIN, ViewMode.B));
        this.addTest(new CommentingTest(Accounts.GUEST, ViewMode.B));
        this.addTest(new SubscriptionsTest(Accounts.ADMIN, ViewMode.A));
        this.addTest(new SubscriptionsTest(Accounts.ADMIN, ViewMode.B));
        this.addTest(new SubscriptionsTest(Accounts.GUEST, ViewMode.B));
        this.addTest(new EditingTest(Accounts.ADMIN, ViewMode.A));
        this.addTest(new EditingTest(Accounts.ADMIN, ViewMode.B));
        this.addTest(new EditingTest(Accounts.GUEST, ViewMode.B));
        this.addTest(new BasicOperationsTest(Accounts.ADMIN, ViewMode.A));
        this.addTest(new BasicOperationsTest(Accounts.ADMIN, ViewMode.B));
        this.addTest(new BasicOperationsTest(Accounts.GUEST, ViewMode.B));
    }
}

但我无法弄清楚如何做这样的事情。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您无法按照列出的方式执行此操作,因为测试类需要具有无参数构造函数。

根据测试结果,您可以选择2个选项:

选项1.使用具有以下参数的子类创建抽象测试类:

使用所有测试制作抽象测试类,然后让子类提供变量信息。抽象类可以在构造函数中使用参数,子类no-arg构造函数使用适当的参数调用super(...)

public abstract class AbstractCommentingTest{

    private Account account;
    private ViewMode mode;

    public AbstractCommentingTest(Account a, ViewMode v){
       this.account=a;
       this.viewMode = v;
    }


    //Put your tests here using the given account and view
    @Test
    public void foo(){

    }

    @Test
    public void bar(){

    }


}

然后是你的具体课程

public class AdminViewACommentingTest extends AbstractCommentingTest{
      //no-arg constructor for JUnit
      public AdminViewACommentingTest(){
          super(Accounts.ADMIN, Viewmode.A);
      }
}

如果有很多选项

,这可以很快失控

选项2:使用Junit参数化测试来获得每个选项组合:

我假设帐户和ViewMode是枚举?如果是这样,您可以轻松地使用values()方法创建所有可能的组合作为参数化测试集的一部分。

@RunWith(Parameterized.class)
public class CommentingTest{

     @Parameters
     public static Collection<Object[]> createData(){
                List<Object[]> data = new ArrayList<Object[]>();

                 for(Accounts account : Accounts.values()){
                    for(ViewMode view : ViewMode.values()){
                         data.put(new Object[]{account, view});
                    }
                  }
                 return data;
    }


    private Account account;
    private ViewMode mode;

    public CommentingTest(Account a, ViewMode v){
       this.account=a;
       this.viewMode = v;
    }

    //Put your tests here using the given account and view
    @Test
    public void foo(){

    }

    @Test
    public void bar(){

    }

}