1

In Mockito we can mock a method, but I'm wondering is it possible to use a different instance altogether?

More especially in my code, I Autowired a Clock as a private field and while testing I want to just use Clock.systemDefaultZone(). I don't want to mock a specific method of it.

The following is my unit test class:

@RunWith(MockitoJUnitRunner.class)
@EnableAutoConfiguration
@SpringBootTest(classes = {Application.class})
@ActiveProfiles(profiles = {"test"})
public class FooTest extends TestCase {

    @Mock
    private Clock clock;

}
Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • 1
    you can't mock static methods using mockito. https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito – Ivan Lymar Nov 20 '19 at 22:48
  • 1
    You don't need a mock then. All you need is `new Foo(Clock.systemDefaultZone())`. Note that your 3 Spring annotations serve no purpose at all since your test doesn't run with the spring runner. You're mixing mockito annotations for unit tests with spring annotations for Spring integration tests. – JB Nizet Nov 20 '19 at 22:48
  • Existing code doesn't do a constructor injection. It used private field injection – Node.JS Nov 20 '19 at 22:50
  • 2
    Then fix it. One of the roles of tests is to detect bugs and bad design, and to improve the quality of the code. – JB Nizet Nov 20 '19 at 22:51
  • @JBNizet I ended up following your advice. Thank you. – Node.JS Dec 02 '19 at 06:46

0 Answers0