Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring引导集成测试:模拟环境接口_Java_Spring Boot_Junit_Environment Variables_Integration Testing - Fatal编程技术网

Java Spring引导集成测试:模拟环境接口

Java Spring引导集成测试:模拟环境接口,java,spring-boot,junit,environment-variables,integration-testing,Java,Spring Boot,Junit,Environment Variables,Integration Testing,在我的Spring安全UserDetailsService中,我注入Environment从env变量读取凭据。 在集成测试中,我想模拟环境接口,以便更改测试的env变量 这是我的测试: @ExtendWith(SpringExtension.class) @SpringBootTest(类=EportfolioApplication.class) @AutoConfigureMockMvc 公共类集成身份验证{ @自动连线 私有MockMvc-MockMvc; @自动连线 私有对象映射器对象映

在我的Spring安全
UserDetailsService
中,我注入
Environment
从env变量读取凭据。 在集成测试中,我想模拟
环境
接口,以便更改测试的env变量

这是我的测试:

@ExtendWith(SpringExtension.class)
@SpringBootTest(类=EportfolioApplication.class)
@AutoConfigureMockMvc
公共类集成身份验证{
@自动连线
私有MockMvc-MockMvc;
@自动连线
私有对象映射器对象映射器;
@试验
void loginCorrectCredentials\u returnsToken()引发异常{
用户=新用户();
user.setUsername(“John Shepard”);
user.setPassword(“Tali”);
MvcResult MvcResult=mockMvc.perform(post(“/login”)
.contentType(“应用程序/json”)
.content(objectMapper.writeValueAsString(用户)))
.andExpect(状态().isOk())
.andReturn();
assertNotNull(
“应存在JWT令牌”,
mvcResult.getResponse().getHeader(“授权”)
);
}
}
最好的方法是什么?

您可以使用。从其javadoc:

在为测试加载
ApplicationContext
之前,应将键值对形式的内联属性添加到Spring
环境中。所有键值对都将作为具有最高优先级的单个测试属性源添加到封闭环境中


下面是一个简单的例子:

@Service
class MyService(
        environment: Environment
) {
    private val foo = environment["com.caco3.demo.foo"]

    fun getFoo() = foo
}
测试:

@SpringBootTest
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
@TestPropertySource(properties = ["com.caco3.demo.foo=test"])
class ApplicationTest(
        private val service: MyService
) {
    @Test
    fun fooIsEqualToTest() {
        assertEquals("test", service.getFoo())
    }
}