[785] | 1 | package testcode;
|
---|
| 2 |
|
---|
| 3 | import static org.junit.Assert.assertEquals;
|
---|
[1017] | 4 | import static org.mockito.ArgumentMatchers.any;
|
---|
[1014] | 5 | import static org.mockito.ArgumentMatchers.eq;
|
---|
[785] | 6 | import static org.mockito.Mockito.mock;
|
---|
| 7 | import static org.mockito.Mockito.when;
|
---|
| 8 |
|
---|
| 9 | import org.junit.Test;
|
---|
[1011] | 10 | import org.junit.internal.runners.JUnit4ClassRunner;
|
---|
| 11 | import org.junit.runner.RunWith;
|
---|
[1070] | 12 | import org.mockito.AdditionalMatchers;
|
---|
[785] | 13 |
|
---|
| 14 | class TestClass {
|
---|
| 15 | public int f(int x) {
|
---|
| 16 | return x + 1;
|
---|
| 17 | }
|
---|
| 18 | }
|
---|
| 19 |
|
---|
[1017] | 20 | class NumberClass {
|
---|
| 21 | public int f(Number x) {
|
---|
| 22 | return x.intValue();
|
---|
| 23 | }
|
---|
| 24 | }
|
---|
| 25 |
|
---|
[785] | 26 | /**
|
---|
| 27 | * Test for mockito translator. This program is going to be translated and run
|
---|
| 28 | * in python.
|
---|
| 29 | */
|
---|
[1011] | 30 | @RunWith(JUnit4ClassRunner.class)
|
---|
[785] | 31 | public class MockitoBasicTest {
|
---|
| 32 |
|
---|
| 33 | /**
|
---|
| 34 | * NOTE NO CONSTRUCTOR. This is needed to check that the proper constructor,
|
---|
| 35 | * matching in this case the implicit superclass TestCase from Python, is
|
---|
| 36 | * created. This is a special case, in normal cases java already enforces
|
---|
| 37 | * all required code including the call to super().
|
---|
| 38 | */
|
---|
| 39 |
|
---|
| 40 | @Test
|
---|
| 41 | public void testStub1() {
|
---|
| 42 | TestClass test = mock(TestClass.class);
|
---|
| 43 | when(test.f(3)).thenReturn(1);
|
---|
| 44 | // the mock did not do any when.thenReturn and should fail
|
---|
| 45 | assertEquals(1, test.f(3));
|
---|
| 46 |
|
---|
| 47 | }
|
---|
| 48 |
|
---|
[1014] | 49 | @Test
|
---|
| 50 | public void testEqMatcher() {
|
---|
| 51 | TestClass test = mock(TestClass.class);
|
---|
| 52 | when(test.f(eq(3))).thenReturn(1);
|
---|
[1015] | 53 | when(test.f(eq(4))).thenReturn(2);
|
---|
[1014] | 54 | assertEquals(1, test.f(3));
|
---|
[1015] | 55 | assertEquals(2, test.f(4));
|
---|
[1014] | 56 | }
|
---|
| 57 |
|
---|
[1017] | 58 | @Test
|
---|
| 59 | public void testAnyOfClass() {
|
---|
| 60 | NumberClass test = mock(NumberClass.class);
|
---|
| 61 | when(test.f(any(Double.class))).thenReturn(1);
|
---|
| 62 | when(test.f(any(Integer.class))).thenReturn(2);
|
---|
| 63 | assertEquals(1, test.f(3d));
|
---|
| 64 | assertEquals(2, test.f(4));
|
---|
| 65 |
|
---|
| 66 | }
|
---|
| 67 |
|
---|
[1070] | 68 | @Test
|
---|
| 69 | public void testNot() {
|
---|
| 70 | TestClass test = mock(TestClass.class);
|
---|
| 71 | when(test.f(AdditionalMatchers.not(eq(3)))).thenReturn(1);
|
---|
| 72 | assertEquals(1, test.f(1));
|
---|
| 73 | assertEquals(1, test.f(2));
|
---|
| 74 | }
|
---|
[785] | 75 | }
|
---|