在我的 Spring Security UserDetailsService
中,我注入(inject) Environment
以从环境变量中读取凭据。
在集成测试中,我想模拟 Environment
接口(interface),以便更改测试的环境变量。
这是我的测试:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = EportfolioApplication.class)
@AutoConfigureMockMvc
public class IntegrationAuth {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
void loginCorrectCredentials_returnsToken() throws Exception {
User user = new User();
user.setUsername("John Shepard");
user.setPassword("Tali");
MvcResult mvcResult = mockMvc.perform(post("/login")
.contentType("application/json")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk())
.andReturn();
assertNotNull(
"JWT Token should be present",
mvcResult.getResponse().getHeader("Authorization")
);
}
}
最好的方法是什么?
最佳答案
您可以使用@TestPropertySource#properties
。来自其 javadoc:
Inlined properties in the form of key-value pairs that should be added to the Spring
Environment
before theApplicationContext
is loaded for the test. All key-value pairs will be added to the enclosing Environment as a single test PropertySource with the highest precedence.
这是一个最小的例子:
@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())
}
}
关于java - Spring Boot集成测试: Mock Environment Interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65544636/