Mockito: How to mock an interface of JodaTime

前端 未结 3 1040
时光说笑
时光说笑 2020-12-09 06:06

I use JodaTime#DateTime, and I need to mock its behavior. Since it is not possible to directly mock JodaTime#DateTime, I create an interface of it<

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 06:25

    You are never giving the PrintProcessor your mock. Making a mock of the object is not the same as giving your mock to an object. So, when you call methods on PrintProcessor, it is operating on a real instance of JodaTime. There are couple of ways to give the PrintProcessor your mock:

    1. Use PowerMockito (make sure you use PowerMock-mockito jar and not PowerMock-easymock jar) and mock the JodaTime constructor to return your mocked Clock object whenNew(JodaTime.class).withNoArguments().thenReturn(mockJodaTime); This will insert your mock wherever a no-arg constructor for JodaTime is used. Note: This will require you to use a mock of the JodaTime class.
    2. Add a setter method for the Clock jodaTime field (which, if only defined in the constructor should probably be final).
    3. Use a Factory for your Clock class and simply return the mock during tests (you can use PowerMockito to mock static methods).
    4. Create a constructor with a Clock parameter and pass in your mock.

提交回复
热议问题