Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Partial mocking example
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