【问题标题】:Spring Boot Integration Test : Mock Environment InterfaceSpring Boot 集成测试:模拟环境接口
【发布时间】:2021-04-09 04:20:51
【问题描述】:

在我的 Spring Security UserDetailsService 中,我注入 Environment 以从 env 变量中读取凭据。 在集成测试中,我想模拟 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")
        );
    }
}

最好的方法是什么?

【问题讨论】:

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


    【解决方案1】:

    您可以使用@TestPropertySource#properties。从它的javadoc:

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


    这是一个最小的例子:

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

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 2021-06-01
      • 2018-03-22
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 2020-12-16
      • 2021-12-03
      • 2015-04-25
      相关资源
      最近更新 更多