@Autowired字段在测试中始终为空,我缺少什么?

时间:2019-11-02 21:48:58

标签: java spring testng autowired

测试属性:

package com.sandbox.test;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:new-test.properties")
public class TestProperties {
    @Getter
    @Value("${homepage.url}")
    private String homePageUrl;
}

配置:

package com.sandbox.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"com.sandbox"})
public class SpringContext {
}

/ src / test / resources中的new-test.properties文件的内容:

homepage.url=https://tst.mysite.com

MyTest类中进行了2次测试,第一个测试无效-第二个测试正常:

package com.sandbox.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.Test;

@ContextConfiguration(classes = {SpringContext.class})
public class MyTest {

    @Autowired
    private TestProperties testProperties;

    @Test
    public void thisDoesntWork() {
        Assert.assertNotNull(testProperties);
        System.out.println(testProperties.getHomePageUrl());
    }

    @Test
    public void thisWorks() {
        AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(SpringContext.class);
        TestProperties testProps = appContext.getBean(TestProperties.class);

        Assert.assertNotNull(testProps);
        System.out.println(testProps.getHomePageUrl());
    }
}

目标是在testProperties中自动连接MyTest字段,而无需使用xml 。但目前是null@Component@ComponentScan注释已经到位,但我缺少什么?..

1 个答案:

答案 0 :(得分:1)

请参见Spring的documentation。可能您的测试需要扩展   AbstractTestNGSpringContextTests 可以自动访问 ApplicationContext 并使自动装配工作。