Use of parameterized tests with JUnit

2019-04-13 03:43发布

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.

For example

 public class MyClass {

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

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

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 ?

2条回答
Explosion°爆炸
2楼-- · 2019-04-13 04:26

recently i started zohhak project. it lets you write:

@TestWith({
   "25 USD",
   "38 GBP",
   "null"
})
public void testMethod(Money money) {
   ...
}
查看更多
时光不老,我们不散
3楼-- · 2019-04-13 04:33

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.

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.

查看更多
登录 后发表回答