Skip to content

Instantly share code, notes, and snippets.

@kntmr
Created February 13, 2017 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kntmr/be7637f08fa6029a3fc122b20814950d to your computer and use it in GitHub Desktop.
Save kntmr/be7637f08fa6029a3fc122b20814950d to your computer and use it in GitHub Desktop.
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