首页 文章

Spring单元测试对象使用空字段自动装配

提问于
浏览
1

我正在尝试在我的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,然后将它们直接设置到我的控制器中 . 但这不是正确的做法 .

所以问题是,为什么自动装配对象的自动装配字段在我的测试类中为null时,它直接在同一测试类中自动装配这些对象,或者我在Weblogic服务器上正常运行代码 .

1 回答

  • 1

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

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

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

    ExampleRestControllerTest

    所以问题是,为什么自动装配对象的自动装配字段在我的测试类中为null时,它直接在同一测试类中自动装配这些对象,或者我在Weblogic服务器上正常运行代码 .

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

相关问题