Unit testing JSPs in embedded mode

2019-02-11 02:15发布

问题:

I am in process of building up a small framework that does unit testing for JSPs. These JSPs have some custom tags, otherwise they are not any special.

Although there are numerous Java unit testing solutions available, I prefer not to use the method where a separate full-blown JSP container is launched, application deployed and results gathered via TCP connection. Typical examples of this case would be Apache Cactus, Selenium, etc. Ideally what I want is to have an embedded solution which is as lightweight as possible (network connection is not being required is a good sign). I have also looked at various mock frameworks but found not a single clean working example when a JSP is compiled/executed during the unit test.

The closest solution I was able to find was using Jetty in embedded mode, or in particular it's ServletTester class, as documented in http://docs.codehaus.org/display/JETTY/ServletTester

Unfortunately the above method only works for servlets but has no mention of JSP. I presume there's a way to programatically hook Jasper servlet into it but can't afford spending a week diving into Jetty/Jasper internals just to get the two integrated. I don't mind using any other JSP/Servlet container as long as it is free and flexibly configurable.

I would appreciate if anyone's got a similar setup and willing to share the experience.

回答1:

Here is a example project that run Jettys ServletTester with jsps.

https://github.com/genthaler/jetty-jsp-unit-test-simple/



回答2:

Take a look at HttpUnit - http://httpunit.sourceforge.net/. It comes bundled with ServletUnit which is an in memory servlet engine that will handle JSPs. This should usually only be used to test the View portion of a properly factored MVC application or to do some Integration/Acceptance tests.

Business logic should be tested directly from the POJOs.