测试属性:
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
类不使用xml中的MyTest
字段。但目前是null
。 @Component
和@ComponentScan
注释到位,但是我缺少什么?..
请参见Spring的documentation。可能您的测试需要扩展AbstractTestNGSpringContextTests可以自动访问ApplicationContext并使自动装配工作。