Created
February 13, 2017 04:39
-
-
Save kntmr/be7637f08fa6029a3fc122b20814950d to your computer and use it in GitHub Desktop.
Partial mocking example
This file contains 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
static class Sample { | |
int value; | |
Sample() { | |
this.value = -1; | |
} | |
Sample(int value) { | |
this.value = value; | |
} | |
int getValue() { | |
return this.value; | |
} | |
boolean method1() { | |
return true; | |
} | |
static void method2() { | |
throw new IllegalStateException(); | |
} | |
} | |
@Test | |
public void test01() { | |
final Sample mock = new Sample(); | |
new Expectations(Sample.class) {{ | |
mock.getValue(); result = 123; | |
}}; | |
Sample sut1 = new Sample(); | |
Sample sut2 = new Sample(1); | |
assertThat(sut1.getValue(), is(123)); // mocked | |
assertThat(sut2.getValue(), is(123)); // mocked | |
assertThat(sut2.value, is(1)); // non-mocked | |
} | |
@Test | |
public void test02() { | |
final Sample sut1 = new Sample(1); | |
new Expectations(sut1) {{ | |
sut1.getValue(); result = 123; | |
Sample.method2(); | |
}}; | |
assertThat(sut1.getValue(), is(123)); // mocked | |
assertThat(sut1.method1(), is(true)); // non-mocked | |
try { | |
Sample.method2(); // mocked | |
} catch (Throwable e) { | |
fail(); | |
} | |
Sample sut2 = new Sample(2); | |
assertThat(sut2.getValue(), is(2)); // non-mocked | |
assertThat(sut2.method1(), is(true)); // non-mocked | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment