【发布时间】:2015-09-11 19:47:24
【问题描述】:
我正在尝试在我的 spring servlet 中为休息服务创建单元测试。但是当控制器对象由@autowire 创建时,它的所有@autowired 字段都是空的。
我的测试类如下,使用 SpringJUnit 运行器和上下文配置集
@ContextConfiguration(locations = "ExampleRestControllerTest-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleRestControllerTest {
@Autowired
private BaseService mockExampleService;
@Autowired
private ExampleRestController testExampleRestController;
ExampleRestControllerTest-context.xml 设置要模拟的服务并将模拟对象注入控制器
<context:annotation-config/>
<import resource="classpath*:example-servlet.xml"/>
<bean id="mockExampleService" class="org.easymock.EasyMock" factory-method="createMock">
<constructor-arg index="0" value="za.co.myexample.example.services.BaseService"/>
</bean>
<bean id="testExampleRestController" class="za.co.myexample.example.rest.controller.ExampleRestController">
<property name="exampleService" ref="mockExampleService"/>
</bean>
控制器使用的其余 bean 定义在 example-servlet.xml 中
<bean id="RESTCodeMapper" class="za.co.myexample.example.rest.util.RESTCodeMapper"/>
<bean id="restProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:RESTServiceCodeMapping.properties"/>
</bean>
连同我的 Jax2BMarshaller。
我的 IDE 可以很好地链接到这些定义,如果我删除任何定义,我会得到预期的“无合格 bean”错误。
我的问题是,当我运行单元测试时,提供的控制器的所有字段都为空
@Controller
public abstract class BaseRestController {
private static Logger LOGGER = Logger.getLogger(BaseRestController.class);
protected final String HEADERS = "Content-Type=application/json,application/xml";
@Autowired
protected RESTCodeMapper restCodeMapper;
@Autowired
protected BaseService exampleService;
@Autowired
protected Jaxb2Marshaller jaxb2Marshaller;
(及其实现类)
@Controller
@RequestMapping("/example")
public class ExampleRestController extends BaseRestController {
当我在我的 Weblogic 服务器中运行正确的代码时,字段会正确填充。更重要的是,如果我直接在我的测试类中添加这些字段,这些字段也会正确地得到@autowired。因此,我可以在我的测试类中 @autowire 这些对象,然后将它们直接设置到我的控制器中。但这不是正确的做法。
所以问题是,当我的测试类直接在同一个测试类中自动装配这些对象时,或者如果我在我的 Weblogic 服务器上正常运行代码时,为什么我的测试类中自动装配对象的自动装配字段为空。
【问题讨论】: