我需要測試一個現在工作正常的servlet。測試Spring託管servlet
servlet需要使用一個Spring服務,所以它被修改爲這樣:
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(
this, config.getServletContext()); // ImageServlet.java line 49
遷移後彈簧4,測試打破了,目前它拋出這個異常:
java.lang.IllegalStateException:
No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.context.support.WebApplicationContextUtils.
getRequiredWebApplicationContext(WebApplicationContextUtils.java:84)
at org.springframework.web.context.support.SpringBeanAutowiringSupport.
processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:107)
at package.ImageServlet.init(ImageServlet.java:49)
at in.nasv.utils.ImageServletTest.accessingImageViaHttp(ImageServletTest.java:45)
下面是ImageServletTest的代碼的部分:
// prepare servlet instance
MockServletConfig config = new MockServletConfig(
new MockServletContextPatched());
ImageServlet servlet = new ImageServlet();
servlet.init(config); // ImageServletTest, line 45
而這種修補CLAS S(不是現在居然打補丁):
public class MockServletContextPatched extends MockServletContext{ }
那我該怎麼做,以避免這種「IllegalStateException異常:沒有找到的WebApplicationContext:沒有註冊的ContextLoaderListener」 ?
你真的需要調用'init()'方法來測試你的Servlet嗎?如果沒有,我建議你只是手動實例化你的Servlet和_inject_它的依賴關係,而不是依賴你的測試中的'SpringBeanAutowiringSupport'。 –
偉大的方法,但它不適用於我的情況。Spring MockServletContext的功能非常有限(沒有setter和getters只返回固定值,dummy Spring!),所以我需要擴展它。我只能通過init()應用它() – joro
Spring的'MockServletContext' ** does **有setter。你認爲Spring的'MockServletContext'有什麼限制?你定製的'MockServletContextPatched'有什麼特別之處? –