繁体   English   中英

使用空字段自动连线的Spring单元测试对象

[英]Spring unit test objects autowired with null fields

我试图在我的spring servlet中为rest服务创建单元测试。 但是,当控制器对象由@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服务器上正常运行代码。

在测试类中,由于上下文配置,@ Autowired对象为空,因此请将其更改为:

@ContextConfiguration(locations = "ExampleRestControllerTest-context.xml")

@ContextConfiguration(locations = "classpath:/ExampleRestControllerTest-context.xml")

ExampleRestControllerTest

所以问题是,当自动连线对象直接在同一测试类中自动连线对象时,为什么自动连线对象的自动连线字段在我的测试类中为空,或者我是否在Weblogic服务器上正常运行代码。

在自动装配对象的构造函数中,它们必须为null。 您可以尝试在自动装配对象中创建@PostConstruct方法,在这种方法中,自动装配对象不能为null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM