在JUnit中使用参数化测试 [英] Use of parameterized tests with JUnit

查看:691
本文介绍了在JUnit中使用参数化测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课,其中一种公共方法非常适合参数化测试.我还读到您通常在项目中的测试用例(带有@Test批注方法的具有多个方法的类)与类之间保持对应关系.是否有可能同时使用Parameterized.class和JUnitCore.class作为运行程序?现在,如果使用参数化,我将无法解决如何设置方法的非参数化测试 在同一测试用例中.我曾考虑过要创建一个套件,然后包括 参数化测试和常规"测试,但是似乎要使名称对测试用例有意义,我将不得不将测试用例的名称绑定到方法的名称,而不是绑定到包含似乎是标准方法的类的类.方式.

I have a class where one of the public methods is a perfect fit for parameterized tests. Also I am reading that you usually keep a correspondence between testcases (a class having multiple methods with @Test annotated methods) and classes in the project. Is it possible somehow to use both Parameterized.class and JUnitCore.class as the runner ? Right now if utilizing Parameterized I can't work out how to setup non-parameterized testing of methods within the same testcase. I have thought about then creating a Suite wich would then include the Parameterized test and "regular" ones, but then it seems that to make names meaningful for testcases, I would have to bind the name of the testcase to the name of the method rather then to the class containing the method which seems to be standard way.

例如

 public class MyClass {

     public int methodSuitableForParameterizedTest(int m){
         // Implementation
     }

     public int methodForRegularTest(int m) {
         // Implmentation
     }
 }

我仍然可以拥有一个包含第一种方法的参数化测试以及第二种方法的非参数化测试的测试用例TestMyclass吗?

Can I still have a single testcase TestMyclass that contains paremeterized testing of the first method as well as non-parameterized testing of the second ?

推荐答案

这很难做到,它涉及到创建自己的运行程序来完成这两项工作,因此我将坚持使用两类解决方案,其中一种是带有参数化的测试和一个没有.

This is quite difficult to do, it involves creating your own runner which does both jobs, so I would just stick to the two class solution, one with the parameterized tests and one without.

问题是双重的,类上的@RunWith注释和构造方法.对于参数化测试,您需要@RunWith(Parameterized.class)和带有参数的构造函数.对于标准测试,构造函数没有参数.然后,JUnit会检查特定的类是否只有一个构造函数.您可以通过创建另一个跑步者来做到这一点,但这并不简单.

The problem is twofold, the @RunWith annotation on the class and the contructor. For a parameterized test, you need @RunWith(Parameterized.class) and a constructor with arguments. For a standard test, the constructor has no parameters. And JUnit checks that a particular class has only one constructor. You can do this by creating another runner, but it's not simple.

在这种情况下,我建议您使用两个测试类.

I would recommend in this case having two test classes.

这篇关于在JUnit中使用参数化测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆