我必须测试某些SLSB的方法,该方法在当前对象上调用另一个方法(使用这个关键字),我需要以某种方式存根。使用“this”关键字调用的Mockito存根方法
考虑以下简化的代码:
@Local
public interface SomeService{
public int someMethod();
public int anotherMethod();
}
@Stateless()
public class SomeServiceImpl{
@EJB
private SomeDAO sDAO;
public SomeServiceImpl(){}
public SomeServiceImpl(SomeDAO sDAO){
this.sDAO = sDAO;
}
@Override
public int someMethod(){
int dbValue = sDAO.getSomeDBValue(); // 1st stub required here
return dbValue + this.anotherMethod(); // 2nd stub required here
}
@Override
public int anotherMethod(){
return 5;
}
}
末梢getSomeDBValue()方法我可以注入模拟到这个类@Mock和@InjectMocks注释,但我不能找出如何正确存根anotherMethod() 。为了存根,我需要在模拟对象上进行确切的操作,所以我试图将当前对象的引用作为参数传递,并且在测试中只传递模拟对象。 例如,如果我的方法是这样的(而不需要存根DAO方法)..
@Override
public int someMethod(SomeServiceImpl sS){
return sS.anotherMethod();
}
我与手动创建的嘲笑测试应该是这样的:
@Test
public void someMethodTest() throws Exception {
SomeServiceImpl sS = mock(SomeServiceImpl.class);
when(sS.someMethod(any(SomeServiceImpl.class))).thenCallRealMethod();
when(sS.anotherMethod()).thenReturn(5);
assertEquals(5, sS.someMethod(sS));
}
方法被调用模拟对象,对象本身的引用作为参数传递,另一个方法被存根。它的工作,但它似乎很丑陋的解决方案,以及如果需要使用注释这样注入我的DAO的模拟:
@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest{
@Mock
SomeDAO sDAO;
//@Mock //I can't use those 2 annotations at once
@InjectMocks
SomeServiceImpl sS;
@Test
public void someMethodTest() throws Exception {
//...
}
}
据我了解@InjectMocks注解用来指示所在班级嘲笑标注有@Mock应注射,但对于我丑陋的解决方案,我需要SomeServiceImpl来模拟。
是我的解决方案,甚至接近正确?我想如何存根anotherMethod()来正确测试someMethod()?传递类的嘲讽实例,我在方法参数中测试哪种方法是个好主意?如果是,我应该如何处理创建含注释的模拟?
使用在物体的Unten测试'Mockito.spy'包装。 –