Search code examples
javajunitmockingjmockit

JMockit behaviour when mocking same class multiple times using @Mocked


I get different output when mocking a class once and when mocking a class two times in a test. I know that @Mocked mocks all instances of a class but am not sure why mocking more than once affects the output of newly created objects. Is this behaviour expected?

Test 1. Prints 10:

 @Test
 public void jmockitTest1(@Mocked final Date d1)
 {
       new NonStrictExpectations()
       {{
            d1.getTime(); returns(10L);
       }};

       System.out.println( d1.getTime() );  // prints 10
       System.out.println( new Date().getTime() ); // prints 10 !
 }

Test 2 with second mocked Date. Prints 0:

 @Test
 public void jmockitTest2(@Mocked final Date d1, @Mocked final Date d2)
 {
       new NonStrictExpectations()
       {{
            d1.getTime(); returns(10L);
       }};

       System.out.println( d1.getTime() );  // prints 10
       System.out.println( new Date().getTime() ); // prints 0 !
 }

Solution

  • The second test, with Date mocked twice, gets "on-instance" matching by default. So, it's as if the expectation was recorded as onInstance(d1).getTime();.

    This difference in mocking behavior is activated automatically merely as a convenience. The only reason to declare multiple mock fields/parameters of the same type in the same test is to have different results from calls to different mocked instances; the automatic "on-instance" matching avoids the need to use onInstance(mock) on each of those instances.