我正在尝试使用mockito编写一个单元测试用例,并且我想注入(inject)一个带有真实参数而不是模拟参数的bean。
该 bean 有一些从 .properties 文件读取的字符串值。
@Component
public class SomeParameters {
@Value("${use.queue}")
private String useQueue;
}
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private A a;
@Autowired
private SomeParameters someParameters;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testMethod() {
if(someParameters.getUseQueue==true){
//do something
}else{
/bla bla
}
}
我的主要目标是在真实场景中运行测试用例。我不想使用模拟值。
我能够通过这种方式注入(inject)带有真实参数的bean。但这是单元测试用例,而不是集成测试。所以我不应该给出applicationContext。您能指导我如何处理这种情况吗?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {
最佳答案
如果您想使用spring-context,那么您应该为您的测试创建一个配置(通过xml或java配置)并仅声明您需要的bean。 For Example
要设置属性,只需声明@TestPropertiesSource("use.queue=someValue")
,否则您需要从测试资源中读取值。
@SpyBean
关于java - 使用mockito注入(inject)带有真实参数的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52755922/