Spring 启动集成测试:模拟环境界面

Spring Boot Integration Test : Mock Environment Interface

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

这是我的测试:

@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 the ApplicationContext 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())
    }
}