java - Spring Boot集成测试: Mock Environment Interface

标签 java spring-boot junit environment-variables integration-testing

在我的 Spring Security UserDetailsS​​ervice 中,我注入(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 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())
    }
}

关于java - Spring Boot集成测试: Mock Environment Interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65544636/

相关文章:

java - 如何在 JUnit 测试用例中设置运行时超时

java - Spring & 没有独特的 bean 类型

java - 删除末尾的多余空间

spring - Websphere 8.5.5.12 - Spring Boot 不工作

java - 如何在 Spring Boot Rest 响应中将 boolean 值序列化为字符串?

java - Spring Boot 2 WebClient响应将JSON转换为HashMap

安卓工作室 : Can not find Run test choice

java - Junit 5 (jupiter) 使用 Maven 进行条件执行

java - 测试无限循环+java

java - 如何 Autowiring Spring TaskExecutor 创建的线程?