我使用 groovy 和 junit 来编写单元测试。我写了一个方法,testBrandIDParam
,测试一些常见的情况,例如 null
参数值或paramID < 0
使用反射。但是,当我测试null
时param,这个方法并不总是有效。我该如何解决这个问题?
@Test
public void testGetDetailBrand() {
GetDetailReqDTO reqDTO = new GetDetailReqDTO();
testBrandIDParam(reqDTO, service, "getDetailBrand");
}
private <T> void testBrandIDParam(T requestDTO, Service service, String testMethod) {
Class requestClazz = requestDTO.getClass();
Class serviceClazz = service.getClass();
java.lang.reflect.Method doTestMethod = serviceClazz.getMethod(testMethod, requestDTO.class);
// test null
CommonRespDTO respDTO = doTestMethod.invoke(service,{null });
Assert.assertTrue(respDTO.getRespCode() == ICommonRespDTO.ResponseCode.FAIL.getCode());
T reqInstance = (T) requestClazz.newInstance();
// req-ID = 0
respDTO = (CommonRespDTO) doTestMethod.invoke(service, reqInstance)
Assert.assertTrue(!respDTO.isSuccess());
brandIDField.setAccessible(false);
}
注:getDetailBrand()
只有一个参数,brandID
.
CommonRespDTO respDTO = doTestMethod.invoke(service,{null });
抛出java.lang.IllegalArgumentException: argument type mismatch
CommonRespDTO respDTO = doTestMethod.invoke(service,new Object[1]{ null });
抛出groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.Object;.call() is applicable for argument types: (service.serviceTest$_testBrandIDParam_closure1) values: [service.serviceTest$_testBrandIDParam_closure1@28236ebc]
Possible solutions: tail(), wait(), any(), max(), last(), wait(long)CommonRespDTO respDTO = doTestMethod.invoke(service,new Object[1]{ null });
产生编译错误:new Objecy[] cannot be applied to groovy.lang.Closure
最佳答案
您需要将Object
数组传递给invoke()
。这有点棘手:
doTestMethod.invoke(service, [null] as Object[])
关于java - 如何使用groovy中的反射调用具有空参数值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698215/