gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:21:19 24 4
gpt4 key购买 nike

测试属性:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com