当junit进行单元测试时,遇到没有返回值的方法,怎么办?
实例
package com.src.unittest;
public class unittest {
private static String stringtest;
public void setvalue(String temp){
stringtest=temp+"123"; //get value: stringtest
}
public String getvalue(){ //return the stringtest value for unit test
return stringtest;
}
}
如果需要进行测试的方法没有返回值,那么这个方法一定会对某个对象做一些操作,比如改变某个属性、变量的值等,否则这这个方法就什么都没做,这是没有任何意义的
对于没有返回值的方法,在进行测试时可以对可观测到的变动进行测试,即要测试它的行为。不同方法有不同的测试策略,具体视情况而定
具体来说,上面所举的例子中,要测试setValue()方法,这个方法的行为我们可以理解为改变了stringtest 的值,我们就可以对stringtest的值进行验证
测试用例可以这样写
import static org.junit.Assert.*;
import org.junit.Test;
import com.beyondsoft.UnitTest;
public class TestUnitTest {
UnitTest tStr = new UnitTest();
@Test
public void testSetvalue() {
tStr.setvalue("123");
assertEquals("123123", tStr.stringtest);
}
}
但是,由于 privatestatic String stringtest; 中stringtest作用域的问题致使不能在测试case中直接调用stringtest
两种解决办法:
1、先将作用域private更改为可测试的范围,如public,验证该方法功能没有问题之后,一定要记得将作用域改回来,但是,这样的话就修改了源代码,这不是最合理的方式
2、使用java反射机制获取stringtest值,进行测试(同样的,私有方法的测试也可以使用反射机制进行测试)
具体实现:
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import org.junit.Test;
import com.beyondsoft.UnitTest;
public class TestUnitTest {
UnitTest tStr = new UnitTest();
@Test
public void testSetvalue(){
Class t = UnitTest.class;
Field field;
try {
field = t.getDeclaredField("stringtest");
field.setAccessible(true); //设置为true,无视java的封装
tStr.setvalue("123");
assertEquals("123123", field.get(t.newInstance()));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
私有方法测试,反射机制的使用:
Method method = targetClass.getDeclaredMethod("方法名", 方法参数类);
method.setAccessible(true);return method.invoke(类的实例, 方法参数值);
Field field = targetClass.getDeclaredField("私有变量名");field.setAccessible(true);
field.set(类的实例, 私有变量值);