模拟具有 @Configuration 注释的 class
Mocking a class having @Configuration annotation
我的springclass有注解@Configuration。我想在 JUnits 中使用 Mockito 来模拟它,但无法这样做。
示例 class:
@ConfigurationProperties(prefix="abc.filter")
@Configuration
@Getter
@Setter
public class ConfigProp {
public String enabled=false;
}
我试图模拟它的方式是:
@Mock private ConfigProp configProp;
和
ConfigProp prop=mock(ConfigProp.class)
但其中 none 有效。
请建议我如何模拟这个 class.
这是一个很常见的问题,太常见了,我开发了一个JUnit测试扩展来解决这个问题:https://github.com/exabrial/mockito-object-injection
我的测试扩展允许您设置一个 @InjectSource
字段以在测试期间设置字符串值(或任何其他对象),而无需诉诸反射 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
}
}
我的springclass有注解@Configuration。我想在 JUnits 中使用 Mockito 来模拟它,但无法这样做。 示例 class:
@ConfigurationProperties(prefix="abc.filter")
@Configuration
@Getter
@Setter
public class ConfigProp {
public String enabled=false;
}
我试图模拟它的方式是:
@Mock private ConfigProp configProp;
和
ConfigProp prop=mock(ConfigProp.class)
但其中 none 有效。 请建议我如何模拟这个 class.
这是一个很常见的问题,太常见了,我开发了一个JUnit测试扩展来解决这个问题:https://github.com/exabrial/mockito-object-injection
我的测试扩展允许您设置一个 @InjectSource
字段以在测试期间设置字符串值(或任何其他对象),而无需诉诸反射 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
}
}