package testcode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.eclipse.jdt.annotation.NonNull; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith; import org.mockito.AdditionalMatchers; class TestClass { public int f(int x) { return x + 1; } } class NumberClass { public int f(Number x) { return x.intValue(); } } /** * Test for mockito translator. This program is going to be translated and run * in python. */ @RunWith(JUnit4ClassRunner.class) public class MockitoBasicTest { /** * NOTE NO CONSTRUCTOR. This is needed to check that the proper constructor, * matching in this case the implicit superclass TestCase from Python, is * created. This is a special case, in normal cases java already enforces * all required code including the call to super(). */ @Test public void testStub1() { final @NonNull TestClass test = mock(TestClass.class); when(test.f(3)).thenReturn(1); // the mock did not do any when.thenReturn and should fail assertEquals(1, test.f(3)); } @Test public void testEqMatcher() { final @NonNull TestClass test = mock(TestClass.class); when(test.f(eq(3))).thenReturn(1); when(test.f(eq(4))).thenReturn(2); assertEquals(1, test.f(3)); assertEquals(2, test.f(4)); } // does not work together with workaround for #396... @Test public void testAnyOfClass() { final @NonNull NumberClass test = mock(NumberClass.class); when(test.f(any(Double.class))).thenReturn(1); when(test.f(any(Integer.class))).thenReturn(2); assertEquals(1, test.f(3d)); assertEquals(2, test.f(4)); } @Test public void testNot() { final @NonNull TestClass test = mock(TestClass.class); when(test.f(AdditionalMatchers.not(eq(3)))).thenReturn(1); assertEquals(1, test.f(1)); assertEquals(1, test.f(2)); } @Test public void testNotEqual() { final @NonNull TestClass a = mock(TestClass.class); final @NonNull TestClass b = mock(TestClass.class); assertFalse(a.equals(b)); } @Test public void testVerify() { final @NonNull TestClass a = mock(TestClass.class); when(a.f(anyInt())).thenReturn(1); a.f(1); a.f(1); verify(a, times(2)).f(1); verify(a, times(2)).f(any(Integer.class)); verify(a, times(0)).f(2); } }