[英]unit tests - one method instead of 50
Could you help me? 你可以帮帮我吗? I have the object with 50 fields (String a, Integer b ...) and I have the method with 'if' statement like this:
我有50个字段(字符串a,整数b ...)的对象,并且具有'if'语句的方法如下:
if( a==null OR b==null OR ...(for any field ) ) {
throw My Exception();
}
I am writing unit test for this method. 我正在为此方法编写单元测试。 I created 50 instantiations of my object like this
我像这样创建了50个实例化对象
1. a=null, <-- only a is null for this instantiation 2. b=null <--- only b is null for this instantiation . . . 50. n=null <--- only n is null for this instantiation
My question is, do I have to write 50 @Test methods for this? 我的问题是,我是否必须为此编写50个@Test方法?
I wrote one @Test method like this but I am not sure that this is correct according to the paradigm of unit tests. 我写了一个这样的@Test方法,但是根据单元测试的范式,我不确定这是正确的。
@Test
public void test(){
for(int a=0;a<50;a++){
try{
//I call the method with my if statament for any of 50 object
}
catch(MyException e){
y++;
}
}
Assert.assert(y,50);
}
I'm writing an answer using a JUnit 4 parameterized test. 我正在使用JUnit 4参数化测试编写答案。 Since you already created 100 different instances of your object, just put that code in the
parameters
method. 由于您已经创建了100个对象的不同实例,因此只需将该代码放入
parameters
方法中即可。
@RunWith(Parameterized.class)
public class MyParameterizedTest {
MyObject value;
public MyParameterizedTest(MyObject value) {
this.value = value;
}
@Parameterized.Parameters
public static List<MyObject> parameters() {
// create a list with 100 different instances of your object...
// return it...
}
@Test(expected = MyException.class)
public void testMethodCallShouldThrowException() throws MyException {
// I call the method with my if statament for any of 100 object
myMethod(value);
}
}
Link to docs: Parameterized 链接到文档: 参数化
This is probably not the answer you like to hear, but the precondition for meaningful unit tests is a reasonable design. 这可能不是您希望听到的答案,但是有意义的单元测试的前提是合理的设计。 Having a class with 100 attributes is definitely a design that can be improved.
具有100个属性的类绝对是可以改进的设计。
So think about redesigning your class first. 因此,请先考虑重新设计您的课程。
Edit: At first sight my statement seems to contradict the Test Driven Design approach where you implement the unit tests without having implemented the classes. 编辑:乍看之下,我的陈述似乎与“测试驱动设计”方法相矛盾,在该方法中,您无需执行类即可实现单元测试。 But as a result this will probably prevent you from ending up with a 100 field class.
但是,结果可能会阻止您以100个字段类结束。 So it is not a contradiction.
因此,这不是矛盾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.