Bal*_*ick 8 java testing servlets freemarker jersey
我开始穿着球衣并尝试使用TDD让freemarker使用它.我想ViewProcessor为我的模板创建一个,但是无法在类中注入servlet上下文.
这是类代码:
@Provider
public class myProcessor implements ViewProcessor<Template> {
[...]
@Context
public ServletContext myContext;
[...]
freemarkerConfiguration.setTemplateLoader(
new WebappTemplateLoader(myContext,
myContext.getInitParameter("freemarker.template.path")));
[...]
}
Run Code Online (Sandbox Code Playgroud)
这是测试代码:
public class myProcessorTest extends JerseyTest {
public static myProcessor mp;
public myProcessorTest() throws Exception{
super(new WebAppDescriptor.Builder("com.domain").build());
}
@Test
public void firstTest(){
mp = new myProcessor();
String path = new String("test.ftl");
Template template = mp.resolve(path);
assertNotNull(template);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用maven与依赖关系如下:
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly</artifactId>
<version>1.5-SNAPSHOT</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
当我部署到我的本地jetty服务器时,我的代码运行正常.但是,如果我想测试我的IDE代码,它没有注入servlet上下文(@Context):myContext是null,当我运行测试:/
我想我错过了一些东西,但我是servlet世界的初学者.
有几种方法可以做到这一点。删除构造函数并实现一个configure()方法,如下所示:
public class myProcessorTest extends JerseyTest {
public static myProcessor mp;
@Override
protected AppDescriptor configure() {
return new WebAppDescriptor.Builder("com.domain")
.contextParam("contextConfigLocation", "classpath:/applicationContext.xml")
.contextPath("/").servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class)
.requestListenerClass(RequestContextListener.class)
.build();
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用 spring 上下文注释您的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MyProcessorTest extends JerseyTest {
public static myProcessor mp;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3148 次 |
| 最近记录: |