如何解决模拟具有@Configuration批注的类
我的spring类具有注释@Configuration。我想在JUnits中使用Mockito模拟它,但无法这样做。 示例类:
@ConfigurationProperties(prefix="abc.filter")
@Configuration
@Getter
@Setter
public class ConfigProp {
public String enabled=false;
}
我要模拟的方式是:
@Mock private ConfigProp configProp;
和
ConfigProp prop=mock(ConfigProp.class)
但是它们都不起作用。 请建议我该如何模拟此类。
解决方法
这是一个非常常见的问题,因此很常见,我开发了一个JUnit测试扩展来解决该问题:https://github.com/exabrial/mockito-object-injection
我的测试扩展允许您在测试过程中设置一个@InjectSource
字段来设置String值(或任何其他对象),而无需使用反射API。例如:
@Controller
public class MyController {
@Value("securityEnabled")
private Boolean securityEnabled;
@Autowired
private Authenticator auther;
@Autowired
private Logger log;
public void doSomething() {
if (securityEnabled) {
auther.something();
} else {
log.warn("sec disabled");
}
}
}
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith({ MockitoExtension.class,InjectExtension.class })
class MyControllerTest {
@InjectMocks
private MyController myController;
@Mock
private Logger log;
@Mock
private Authenticator auther;
@InjectionSource
private Boolean securityEnabled;
@Test
void testDoSomething_secEnabled() throws Exception {
securityEnabled = Boolean.TRUE;
myController.doSomething();
// wahoo no NPE! Test the "if then" half of the branch
}
@Test
void testDoSomething_secDisabled() throws Exception {
securityEnabled = Boolean.FALSE;
myController.doSomething();
// wahoo no NPE! Test the "if else" half of branch
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。