[英]How do I mock certain objects of a class being tested?
I've the below class that I want to test: 我有下面的课程要测试:
@Component
public class ToBeTested {
@Autowired
private HelperA helperA;
@Autowired
private HelperB helperB;
... //10 other such helpers
}
I want to mock ONLY HelperA class. 我只想模拟HelperA类。 How do I do this in jUnit? 如何在jUnit中执行此操作? I do not want to mock the other helper classes. 我不想嘲笑其他助手类。 Nor do I want to write @Spy & @Resource for all of the helpers and use @InjectMocks in the test case. 我也不想为所有助手编写@Spy&@Resource并在测试用例中使用@InjectMocks。
Is there a way for me to inject only the mock of HelperA into the ToBeTested class in the test case? 我有办法只将HelperA的模拟注入测试用例中的ToBeTested类吗?
To summarize, you want to use a mocked HelperA
but an @Autowired
HelperB
? 总而言之,您要使用HelperA
但要使用@Autowired
HelperB
?
I wrote an article on this that can help: http://www.sleepeasysoftware.com/how-to-mock-out-a-deeply-nested-class-in-spring-without-going-insane/ 我写了一篇对此有所帮助的文章: http : //www.sleepeasysoftware.com/how-to-mock-out-a-deeply-nested-class-in-spring-without-going-insane/
To summarize, put this at the top of your test class: 总结一下,将其放在测试类的顶部:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ASubclassOfYourRealConfig.class)
Then you create ASubclassOfYourRealConfig
to look like this: 然后,创建ASubclassOfYourRealConfig
如下所示:
public class ASubclassOfYourRealConfig extends YourRealConfig {
@Bean
public HelperA getHelperA() {
return mock(HelperA.class);
}
}
In your test class, you can @Autowire
HelperA
like normal, but it will actually be mocked by Mockito in that test. 在测试类中,您可以像正常HelperA
一样使用@Autowire
HelperA
,但实际上Mockito将在该测试中模拟它。
If you ONLY want helperB, then you'll need @InjectMocks
. 如果仅需要helperB,则需要@InjectMocks
。
@RunWith(MockitoJUnitRunner.class)
public class MyTest() {
@InjectMocks
public ToBeTested toBeTested;
@Mock
private HelperB helperB;
...your tests go here
}
Of course, this will leave your helperA null
. 当然,这将使您的helperA为null
。 If you want to have both, you will simply need a Spring configuration for your tests, set helperB as a mock bean (via factory methods) and run the whole thing with the SpringJUnit4ClassRunner
) 如果您想同时拥有两者,则只需为测试配置一个Spring配置,将helperB设置为模拟bean(通过工厂方法),然后使用SpringJUnit4ClassRunner
运行整个SpringJUnit4ClassRunner
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.