Spring boot 模拟具有@Configuration注释的类
我的spring类有注解@Configuration。我想在JUnits中使用Mockito来模拟它,但无法这样做。 示例类:Spring boot 模拟具有@Configuration注释的类,spring-boot,junit,mockito,Spring Boot,Junit,Mockito,我的spring类有注解@Configuration。我想在JUnits中使用Mockito来模拟它,但无法这样做。 示例类: @ConfigurationProperties(prefix="abc.filter") @Configuration @Getter @Setter public class ConfigProp { public String enabled=false; } 我试图嘲弄它的方式是: @Mock private ConfigPro
@ConfigurationProperties(prefix="abc.filter")
@Configuration
@Getter
@Setter
public class ConfigProp {
public String enabled=false;
}
我试图嘲弄它的方式是:
@Mock private ConfigProp ConfigProp代码>
及
但它们都不起作用。
请建议我如何模拟这个类。这是一个非常常见的问题,非常常见,我开发了一个JUnit测试扩展来解决这个问题:
我的测试扩展允许您在测试期间设置@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
}
}
这是一个非常常见的问题,所以很常见,我开发了一个JUnit测试扩展来解决这个问题:
我的测试扩展允许您在测试期间设置@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
}
}
你能给我看一下你的测试课的代码吗?如果没有它,很难判断您是如何运行测试的。您能展示一下测试类的代码吗?如果没有它,很难判断您是如何运行测试的。