在测试init方法中模拟Thread.currentThread()。getContextClassLoader()

时间:2014-06-07 16:04:01

标签: java testing junit static mocking

我有下一段代码:

public void init() {
    facultyList = new ArrayList<>();
    localeFile = new Properties();
    try {
        localeFile.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(loadFileName()));
    } catch (IOException | NullPointerException e) {
        LOG.error("Host: " + ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRemoteHost()
                + " | Error in constructing of LocaleModel. More: " + e);
    }
}

模拟Thread.currentThread().getContextClassLoader()的任何可能解决方案或如何测试此catch块?

1 个答案:

答案 0 :(得分:2)

您可以设置自定义上下文类加载器。跟踪原始上下文类加载器并在测试完成后将其重新置于上下文中非常重要。

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setContextClassLoader(java.lang.ClassLoader)