【发布时间】:2015-01-28 07:08:40
【问题描述】:
我有一个班级 Service 我想测试它。基本上,我面临一个问题,因为我希望 Service 对象被部分模拟。只有obj1 应该被嘲笑,其他的合作者应该是真实的。我的代码是这样的:
@Component
public class Service {
@Autowired
Object1 obj1;
@Autowired
Object2 obj2;
public void validate(){
obj1.isValid();
obj2.isActive();
}
}
现在在测试上述Service 类的验证方法时,我想在调用obj2 的实际实现时模拟obj1.isValid() 方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:conf/test-context.xml"})
public class ServiceTest {
@InjectMocks
Service service;
@Mock
OBject1 obj1;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testValidate (){
service.validate();
//assert and other stuff
}
}
此测试失败,当我调试验证方法时,我发现obj1 实例在Service 类中按预期注入,但obj2 以null 注入。因此测试失败...
有什么方法可以实现吗?
更新 当我读到一些 SO 答案时,我使用了 springockito。我将以下内容添加到测试类中,如下所示,但结果仍然相同:
@ReplaceWithMock
@Autowired
Object2 obj2
【问题讨论】:
标签: spring unit-testing mocking mockito spring-test