java - Spring Boot Integration Test : Mock Environment Interface
问题描述
In my Spring Security UserDetailsService
, I inject Environment
to read credentials from env variables.
In an integration test, I would like to mock the Environment
interface in order to change the env variables for the tests.
Here is my Test :
@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")
);
}
}
What would be the best approach for this ?
解决方案
You can use @TestPropertySource#properties
. From its 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.
Here is a minimal example:
@Service
class MyService(
environment: Environment
) {
private val foo = environment["com.caco3.demo.foo"]
fun getFoo() = foo
}
Test:
@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())
}
}
推荐阅读
- ubuntu - 詹金斯在“git pull”上失败
- machine-learning - 自动编码器中使用的时期数取决于数据集的维度?
- javascript - this.state 在 ReactJs 组件中为 NULL
- python - 如何在 Python 中查找字符串中的字母
- mysql - MySQL查询与两个不同表的计数之间的减法
- python - 在列表python中拆分Mac地址
- python - 无法在 Python 中使用 WlanGetAvailableNetworkList 获取所有可用网络
- c# - 带有 RibbonComboBox 的 WPF 绑定警告
- azure - 如何配置 Azure AD 权限以从 WebJob 控制台应用程序访问 Microsoft Graph?
- javascript - 以“错误”顺序导入 Web 组件时出错