无法从JUnit的Spring Boot中读取应用程序属性?

Nital

我有一个JUnit测试,我想针对REST已经在我的计算机上指定端口运行的服务运行。已经使用对该REST服务进行了测试Postman并且效果很好。

这里的计划是通过将RESTURL外部化到属性文件中来使URL可配置。因此,我尝试了以下操作,JUnit该类无法读取属性文件的值。

StoreClientTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@PropertySource("classpath:application.properties")
public class StoreClientTest {

    private static final String STORE_URI = "http://localhost:8084/hpdas/store";
    private RestTemplate restTemplate;

    @Value("${name}")
    private String name;


    @Before
    public void setUp() {
        restTemplate = new RestTemplate();
    }


    @Test
    public void testStore_NotNull() {
        //PRINTS ${name} instead of abc ?????
        System.out.println("name = " + name);
        assertNotNull(restTemplate.getForObject(STORE_URI, Map.class));
    }


    @After
    public void tearDown() {
        restTemplate = null;
    }

}

src \ test \ main \ resources \ application.properties

name=abc
Minjun Yu

首先,您需要为测试创建一个应用程序上下文配置

@SpringBootApplication
@PropertySource(value = "classpath:application.properties")
public class TestContextConfiguration {

}

其次,让您的测试班使用此配置

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TestContextConfiguration.class)
public class StoreClientTest {

    @Value("${name}")
    private String name;
    // test cases ..
}  

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Spring Boot应用程序中的会话

我如何使用Spring Boot应用程序从IBM MQ中读取消息?

无法在Junit测试中自动装配JpaRepository-Spring Boot应用程序

Tomcat不读取Spring-Boot应用程序属性

在Spring Boot应用程序中从Zookeeper中读取类(带下划线的路径)

Spring Boot多模块应用程序中的JUnit 4 Test无法自动装配服务

无法加载在Docker中运行的Spring Boot应用程序

如何在ReactJs应用程序中读取Spring Boot application.properties?

在Spring Boot应用程序中读取清单文件

如何在Spring Boot应用程序中的静态字段上读取属性?

Spring Boot应用程序中的NonUniqueResultException

如何在Spring Boot应用程序中读取和存储APK元数据

Intellij Spring Boot应用程序无法在Tomcat中运行

无法在Spring Boot应用程序中配置ViewResolver

无法在IntelliJ中启动Spring Boot + thymeleaf应用程序

无法从Spring-boot应用程序中的Consul读取配置

在Spring Boot应用程序中无法解析占位符

在Spring Boot应用程序中从第三方jar读取属性

无法启动应用程序。TypeError:无法读取getFieldsJsonSchemaFor中未定义的属性“ definition”

在Spring Boot应用程序中无法解析表“'xx”

无法在Spring Web应用程序中打开属性文件

无法从Junit Spring加载属性

Spring Boot应用程序无法在CloudFoundry中启动

JUnit Spring Boot应用程序-无法自动装配字段

无法在 Junit 测试中覆盖 Spring-Boot 应用程序属性

类型错误:无法读取 Angular 应用程序中未定义的属性“长度”

Spring Boot 应用程序未从 Spring Cloud Config Server 读取属性值

如何读取库内的spring boot应用程序属性信息

反应问题无法在测验应用程序中读取未定义的属性(读取“地图”)?