2016-06-08 131 views
0

我使用groovy和junit编写单元测试。我写了一个方法testBrandIDParam来测试一些常见的情况,如null参数值或paramID < 0使用反射。但是,当我测试null参数时,此方法并不总是有效。我怎么解决这个问题?如何使用groovy中的反射调用具有null参数值的方法?

@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

  1. CommonRespDTO respDTO = doTestMethod.invoke(service,{null });
    抛出

    java.lang.IllegalArgumentException: argument type mismatch

  2. 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: [[email protected]]
    Possible solutions: tail(), wait(), any(), max(), last(), wait(long)

  3. CommonRespDTO respDTO = doTestMethod.invoke(service,new Object[1]{ null });
    产生编译错误:

    new Objecy[] cannot be applied to groovy.lang.Closure

+0

很难说出你在问什么,但我最好的猜测是你使用Java数组语法'{}'而不是'[]'为Groovy。 – chrylis

+0

如何在groovy中使用null参数调用方法? –

回答

3

您需要的Object秒的阵列传递到invoke()。这是有点棘手:

doTestMethod.invoke(service, [null] as Object[]) 
+0

Thanks.It真的有用。 –

相关问题