If you want to Mock only some methods of the class called from the class under test
JMockit 1.46
public class Sample {
@Inject
Hoge hoge;
public String getHoge() {
return hoge.getHoge() + hoge.getHogeUpper();
}
}
I'm using Hoge's method injected from the class under test. This is a workaround if you want to partially mock the Hoge.
public class Hoge {
public String getHoge() {
return "hoge";
}
public String getHogeUpper() {
return null;
}
}
Please assume that getHoge has been implemented and getHogeUpper has not been implemented yet.
public class SampleTest {
@Tested
Sample sample;
@Injectable
Hoge hoge;
/**
*A case where you want to Mock only some methods of the class called from the class under test.
*The test fails.
*/
@Test
public void test() {
new Expectations(hoge) {{
hoge.getHogeUpper();
result = "HOGE";
}};
String actual = sample.getHoge();
assertThat(actual, is("hogeHOGE")); //actual becomes null HOGE
}
}
Since the class under test uses Inject, I would normally like to inject instances with @Tested and @Injectable in JMockit, but that would cause the test to fail. The reason is that @Injectable will empty all Hoge methods.
public class SampleTest2 {
Sample sample = new Sample();
/**
*A case where you want to Mock only some methods of the class called from the class under test.
*The test succeeds.
* @throws Exception
* @throws NoSuchFieldException
*/
@Test
public void test() throws NoSuchFieldException, Exception {
Hoge hoge = new Hoge();
new Expectations(hoge) {
{
hoge.getHogeUpper();
result = "HOGE";
}
};
//Set a partially Mocked hoge in the private field of Sample
Field field = sample.getClass().getDeclaredField("hoge");
field.setAccessible(true);
field.set(sample, hoge);
String actual = sample.getHoge();
assertThat(actual, is("hogeHOGE"));
}
}
See below for more information on partial Mock. https://jmockit-ja.nyamikan.net/tutorial/Mocking.html#partial The test is successful by setting the partially Mocked Mock instance to the test target class by reflection.
In older versions of JMockit, only part of it was Mocked with MockUp
Recommended Posts