我有一个小问题。我认为这是一个典型的问题。但是,我找不到很好的例子。我的应用程序使用的是泽西岛。我想通过客户端测试控制器作为测试。控制器有私有字段 - StudentService。当我调试测试时,我看到该字段为空。这会导致错误。我需要注入这个领域。我试过这个:我的控制器
@Path("/student")
@Component
public class StudentResourse {
@Autowired
private StrudentService service; // this field Spring does not set
@Path("/getStudent/{id}")
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Student getStudent(@PathParam("id") long id) {
return service.get(id);
}
}
我的 JUnit 测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config.xml")
@TestExecutionListeners({ DbUnitTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
public class StudentResourseTest extends JerseyTest {
private static final String PACKAGE_NAME = "com.example.servlet";
private static final String FILE_DATASET = "/data.xml";
@Autowired
private StudentService service; // this field is setted by Spring, but I do not need this field for test
public StudentResourseTest() {
super(new WebAppDescriptor.Builder(PACKAGE_NAME).build());
}
@Override
protected TestContainerFactory getTestContainerFactory() {
return new HTTPContainerFactory();
}
@Override
protected AppDescriptor configure() {
return new WebAppDescriptor.Builder("restful.server.resource")
.contextParam("contextConfigLocation",
"classpath:/config.xml").contextPath("/")
.servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class)
.requestListenerClass(RequestContextListener.class).build();
}
@Test
@DatabaseSetup(FILE_DATASET)
public void test() throws UnsupportedEncodingException {
ClientResponse response = resource().path("student").path("getStudent")
.path("100500").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
Student student = (Student) response.getEntity(Student.class);
} }
我猜,这个问题出在测试课上。因为,当我在测试中运行我的应用程序时,我可以直接请求学生并且一切正常。但是当我测试类时,控制器的内部字段没有设置。如何修复这个错误?感谢您的回答。
这是在我的 config.xml
<context:component-scan base-package="com.example" />
<bean id="StudentResourse" class="com.example.servlet.StudentResourse">
<property name="service" ref="studentService" />
</bean>
<bean id="service" class="com.example.service.StudentServiceImpl" />