java - @Autowired 字段在测试中始终为空,我错过了什么?

标签 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());
    }
}

目标是在MyTest类中不使用xml Autowiring testProperties字段。但目前它是null@Component@ComponentScan 注释已到位,但我缺少什么?..

最佳答案

参见documentation Spring 的。可能你的测试需要延长 AbstractTestNGSpringContextTests 自动访问 ApplicationContext 并使 Autowiring 工作。

关于java - @Autowired 字段在测试中始终为空,我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675596/

相关文章:

java - 需要使用 TestNG 在 java 类中循环

java - 频繁发送到spring-websocket session : lost in transit

spring - 具有Spring-Boot/安全性的Null @AuthenticationPrincipal

testng - 将自定义对象传递给 TestNG 结果监听器

java - 在STS上运行Spring项目出现ServletException错误

java - 上课地点

java - 使用并行用户和登录验证码进行自动化测试(使用 selenium webdriver)

java - 用 Java 实现 IDManager - 高效的方法

java - Hive 中关于 EOF 的 ParseException

java - 使用 Angular 参数上传文件