微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Junit测试中对私有函数传递null [code.getDeclaredMethod] [method.invokeserviceTest,“ aaa”,new Object [] {null}发生错误]

如何解决如何在Junit测试中对私有函数传递null [code.getDeclaredMethod] [method.invokeserviceTest,“ aaa”,new Object [] {null}发生错误]

我想测试参数为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应该可以正常工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。