在Spring中实例化mock对象时,如何设置Mockito“when”方法



这个答案中描述的方法最适合我实例化mock对象。

<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.package.Dao" /> 
</bean> 

但是,我还需要设置Mockito when方法。

我可以在XML中做到这一点吗?或者这是唯一的方法,比如:

when( objectToBestTested.getMockedObject()
     .someMethod(anyInt())
    ).thenReturn("helloWorld");

在我的测试用例中?

我之所以这么问,是因为我不需要MockedObject的getter,我只想添加一个getter,这样我就可以测试ObjectToBeTested了。

这是我如何将Mockito与Spring一起使用的方法。

假设我有一个使用服务的控制器,这个服务注入自己的DAO,基本上有这个代码结构。

@Controller
public class MyController{
  @Autowired
  MyService service;
}
@Service
public class MyService{
  @Autowired
  MyRepo myRepo;
  public MyReturnObject myMethod(Arg1 arg){
     myRepo.getData(arg);
  }
}
@Repository
public class MyRepo{}

下面的代码用于junit测试用例

@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest{
    @InjectMocks
    private MyService myService;
    @Mock
    private MyRepo myRepo;
    @Test
    public void testMyMethod(){
      Mockito.when(myRepo.getData(Mockito.anyObject()).thenReturn(new MyReturnObject());
      myService.myMethod(new Arg1());
    }
}

如果您使用的是独立的应用程序,请考虑下面的mock。

@RunWith(MockitoJUnitRunner.class)
public class PriceChangeRequestThreadFactoryTest {
@Mock
private ApplicationContext context;
@SuppressWarnings("unchecked")
@Test
public void testGetPriceChangeRequestThread() {
    final MyClass myClass =  Mockito.mock(MyClass.class);
    Mockito.when(myClass.myMethod()).thenReturn(new ReturnValue());
    Mockito.when(context.getBean(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(myClass);
    }
}

我真的不喜欢在应用程序上下文中创建mock-bean,但如果你真的让它只适用于你的单元测试。

最新更新