使用 mockito 注入带有真实参数的 bean
inject bean with real parameters with mockito
我正在尝试用 mockito 编写一个单元测试用例,我想注入一个带有真实参数而不是模拟参数的 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
}
}
我的主要 objective 是 运行 具有真实场景的测试用例。我不想使用模拟值。
我能够以这种方式注入带有真实参数的bean。但这是单元测试用例,而不是集成测试。所以我不应该给applicationContext。你能指导我如何处理这种情况吗?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {
如果你想使用 spring-context 那么你应该创建一个配置(通过 xml 或 java 配置)您的测试并仅声明您需要的 bean。 For Example
要设置属性,只需声明 @TestPropertiesSource("use.queue=someValue")
否则您需要从测试资源中读取值。
PS。还要检查 特别是 @SpyBean
如果您想使用真实属性,则使用 Properties 对象加载 属性 文件并通过从 Properties 对象获取值来模拟值。
我正在尝试用 mockito 编写一个单元测试用例,我想注入一个带有真实参数而不是模拟参数的 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
}
}
我的主要 objective 是 运行 具有真实场景的测试用例。我不想使用模拟值。
我能够以这种方式注入带有真实参数的bean。但这是单元测试用例,而不是集成测试。所以我不应该给applicationContext。你能指导我如何处理这种情况吗?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {
如果你想使用 spring-context 那么你应该创建一个配置(通过 xml 或 java 配置)您的测试并仅声明您需要的 bean。 For Example
要设置属性,只需声明 @TestPropertiesSource("use.queue=someValue")
否则您需要从测试资源中读取值。
PS。还要检查 @SpyBean
如果您想使用真实属性,则使用 Properties 对象加载 属性 文件并通过从 Properties 对象获取值来模拟值。