问题描述
我想测试参数为null时方法的行为。 我尝试如下所示,但出现粗略类型错过匹配错误。我该怎么做才能进行测试? 我安装了Jmockit。但我不知道如何使用。
java.lang.IllegalArgumentException:参数类型不匹配 在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处
实际代码
@Test
public void testLogic() throws illegalaccessexception,IllegalArgumentException,InvocationTargetException,NoSuchMethodException,SecurityException {
Service serviceTest = new Servicetest();
int expected = false;
Method method = Service.class.getDeclaredMethod("testMethod",String.class,String.class) ;
method.setAccessible(true);
boolean actual = (boolean)method.invoke(serviceTest,"aaa",new Object[]{null});
assertEquals(false,actual);
}
测试代码
private boolean testMethod(String test,String testNull) throws IOException
{
if(testNull== null)
{
return false;
}
return true;
}
解决方法
我不明白为什么您的代码中会包含所有多余的垃圾。为什么这行不通?
@Test
public void testLogic() {
ServiceTest serviceTest = new ServiceTest();
boolean expected = false;
boolean actual = serviceTest.testMethod( "aaa",null );
assertEquals( expected,actual );
}
如果您唯一的问题是如何使用反射调用方法,请尝试删除该数组。
boolean actual = (boolean)method.invoke(serviceTest,"aaa",null );
var args应该可以正常工作。