java - 使用 Mockito 测试 Spring 环境配置文件
问题描述
Spring Framework 的最新版本已弃用 Environment.acceptsProfiles(String ...)以支持Environment.acceptsProfiles(Profiles ...)
在我的一个应用程序中更新它使测试变得更加困难,这里有一些测试代码来演示这个问题:
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.core.env.StandardEnvironment;
public class EnvironmentProfilesTest {
@Test
public void testItWithRealEnvironment() {
System.setProperty(StandardEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "adrian");
Environment environment = new org.springframework.core.env.StandardEnvironment();
ToBeTested toBeTested = new ToBeTested(environment);
assertTrue(toBeTested.hello("adrian"));
}
@Test
public void testItWithMocklEnvironment() {
Environment environment = mock(Environment.class);
when(environment.acceptsProfiles(Profiles.of("adrian"))).thenReturn(true);
ToBeTested toBeTested = new ToBeTested(environment);
assertTrue(toBeTested.hello("adrian"));
}
private static class ToBeTested {
private Environment env;
public ToBeTested(Environment env) {
this.env = env;
}
public boolean hello(String s) {
return env.acceptsProfiles(Profiles.of(s));
}
}
}
旧版本使用字符串参数来接受Profiles 很容易模拟。我究竟做错了什么?感觉 Profiles 类可能会使 equals() 方法受益?
解决方案
这不是春天,它只是不正确的方法。正如我所看到的,问题出在这部分代码中:
when(environment.acceptsProfiles(Profiles.of("adrian"))).thenReturn(true);
您使用 mockEnvironment
并尝试捕获Profiles
类的实例,例如:
.acceptsProfiles(eq(Profiles.of("adrian")))
。您无法捕获它,因为您在方法中创建了另一个实例boolean hello(String s)
并且Environment
永远不会返回 true。
您刚刚描述了模拟的不正确行为,Environment
您可以修复它:
放any
@Test
public void testItWithMocklEnvironment() {
Environment environment = mock(Environment.class);
when(environment.acceptsProfiles(any(Profiles.class))).thenReturn(true);
ToBeTested toBeTested = new ToBeTested(environment);
assertTrue(toBeTested.hello("adrian"));
}
或 不使用模拟(我认为这就是你要找的):
@Test
public void testItWithMocklEnvironment() {
Environment environment = new org.springframework.core.env.StandardEnvironment();
((StandardEnvironment) environment).setActiveProfiles("adrian");
ToBeTested toBeTested = new ToBeTested(environment);
assertTrue(toBeTested.hello("adrian"));
}
推荐阅读
- actions-on-google - detect/prevent keyboard input on Google Action
- java - Get a BigInt value from a resultset (oracle db) in java
- google-colaboratory - Restricted access issues - Google Colaboratory
- arrays - Jolt:如何合并来自不同数组的一个数组元素
- javascript - 在 useEffect 中设置状态
- flutter - 如何通过 Flutter 中的 Inherited Widget 获取当前位置并在树内传递?
- css - 如何在 React 应用程序中的 SVG 中引用 Sass 样式表
- xml - 如何使用 FLWOR 查询合并 XML 文件中元素的相应数据?
- sql - 如何选择一组记录是 ID 存在于其中一个
- javascript - 使用 javascript 正则表达式获取第一个 url 段