使用JUnit测试受保护的方法 [英] Testing protected method with JUnit

查看:440
本文介绍了使用JUnit测试受保护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试的方法是protected.在我的测试案例中,我已经使用Reflection来访问该方法,但是我不确定自己是否以正确的方式进行操作.

I am testing a method which is protected. In my test case I've used Reflection to access the method but I am not exactly sure whether I am doing it in a right way.

要测试的方法:

protected void checkORCondition( Map<String, Message> messagesMap ) throws EISClientException
{
    Message message = containsAMessageCode(getMessageCodes(), messagesMap);
    if(message!=null)
    {
        throw new EISClientException("One of the specified message code matched returned errors." + 
                message.getMessageCode() + ": " + message.getMessageType() + ": " + message.getMessageText());

    }
}

JUnit测试用例:

JUnit test case:

@Test
public void testcheckORCondition() throws Exception {
    Class clazz = MessageToExceptionPostProcessFilter.class;
    Object object = clazz.newInstance();

    Method method = clazz.getDeclaredMethod("checkORCondition", new Class[]{Map.class});
    method.setAccessible(true);

    String string = new String();
    string = "testing";

    Message message = new Message();
    message.setMessageCode("200");

    Map<String, Message> map = new HashMap<String, Message>();
    map.put(string, message);

    assertEquals("testing", string);
    assertEquals("200", message.getMessageCode());  
}

我的JUnit通过了,但不确定它是否在方法内.

My JUnit passes but not sure if it going inside the method.

推荐答案

最好的方法是将受保护的方法置于相同的程序包名称下进行测试.这将确保它们可访问.检查junit常见问题页面 http://junit.org/faq.html#organize_1

Best way is to put the protected methods under same package name under test. This will ensure that they are accessible. Check junit FAQ page http://junit.org/faq.html#organize_1

这篇关于使用JUnit测试受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆