Java Spring引导集成测试:模拟环境接口
在我的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; @自动连线 私有对象映射器对象映
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())
}
}