Created
December 13, 2022 04:20
-
-
Save alexanderankin/7bd2678ab29798f6ab1a2c8a520ca0d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.junit.jupiter.api.BeforeEach; | |
| import org.junit.jupiter.api.Nested; | |
| import org.junit.jupiter.api.Test; | |
| import org.mockito.Mockito; | |
| import static org.mockito.ArgumentMatchers.anyInt; | |
| import static org.mockito.Mockito.when; | |
| public class ExampleTest { | |
| @Test | |
| void test() { | |
| // A a = new A(); | |
| // B b = new B(); | |
| // a.b = b; | |
| // | |
| // System.out.println(a.m()); | |
| // a.b.variable = "def"; | |
| // System.out.println(a.m()); | |
| // objective: test a, without executing ANY B code | |
| // AT ALL!! | |
| A aWithMocking = new A(); | |
| B withMocking = Mockito.mock(B.class); | |
| aWithMocking.b = withMocking; | |
| // now, want to control what b does, but without any code inside it | |
| // mockito offers a way to control a mock from outside the class: | |
| // when you call a method this way, return this value | |
| when(withMocking.method()).thenReturn("def"); | |
| System.out.println(aWithMocking.m()); | |
| } | |
| static class A { B b; String m() { String s = b.method(); return s.toUpperCase(); } } | |
| static class B { | |
| // a piece of code inside B to control what b does | |
| String variable = "abc"; | |
| String method() { | |
| return variable; | |
| } | |
| } | |
| ///////////////// | |
| static class Someone { | |
| NormalCode normalCode; | |
| } | |
| // test for someone who uses Normal Code | |
| @Nested | |
| class SomeoneWhoUsesNormalCodeTest { | |
| Someone classUnderTest = new Someone(); | |
| @BeforeEach | |
| void setup() { | |
| classUnderTest.normalCode = Mockito.mock(NormalCode.class); | |
| } | |
| @Test | |
| void test() { | |
| NormalCode mock = classUnderTest.normalCode; | |
| // future invocations of the mock will follow the below logic | |
| // not the logic of the NormalCode class, because it is not available | |
| // in this test | |
| when(mock.returnValue(1)).thenReturn(1); | |
| when(mock.returnValue(-1)).thenReturn(2); | |
| when(mock.returnValue(anyInt())).thenReturn(3); | |
| System.out.println(mock.returnValue(10)); | |
| System.out.println(mock.returnValue(10)); | |
| System.out.println(mock.returnValue(10)); | |
| System.out.println(mock.returnValue(10)); | |
| System.out.println(mock.returnValue(10)); | |
| } | |
| } | |
| static class NormalCode { | |
| int returnValue (int input) { | |
| return input > 0 ? 1 : 2; | |
| } | |
| } | |
| } |
Author
alexanderankin
commented
Dec 13, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment