spring引导集成测试:模拟环境接口

vdzxcuhz  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(417)

在我的Spring安全 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")
        );
    }
}

最好的方法是什么?

68de4m5k

68de4m5k1#

你可以用 @TestPropertySource#properties . 从它的javadoc:
应添加到spring的键值对形式的内联属性 EnvironmentApplicationContext 为测试加载。所有键值对都将作为具有最高优先级的单个测试属性源添加到封闭环境中。
下面是一个简单的例子:

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

相关问题