Use of parameterized tests with JUnit

末鹿安然 提交于 2019-12-06 09:24:58

问题


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 ?


回答1:


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.




回答2:


recently i started zohhak project. it lets you write:

@TestWith({
   "25 USD",
   "38 GBP",
   "null"
})
public void testMethod(Money money) {
   ...
}


来源:https://stackoverflow.com/questions/9080505/use-of-parameterized-tests-with-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!