In JUnit using Mockito and Powermock, I had to mock the processing of the parent class using super, so I made a note of it. If you look it up, you can use PowerMockito.suppress () quite a bit, but if you use suppress (), it will only be skipped, and you should return the mock object you expected. I was in a state where I couldn't execute the subsequent processing of JUnit successfully.
The sample code is shown below. The DTO class is omitted.
Parent class
public class Parent {
	public OutputDto execute (InputDto input) {
		System.out.println("Parent#execute()");
		OutputDto out = new OutputDto();
		out.setText(input.getText());
		return out;
	}
}
Child class
public class Child extends Parent {
	public OutputDto execute (InputDto input) {
		System.out.println("Child#execute()");
		OutputDto out = super.execute(input);
		out.setText(out.getText()+" updated in Child.");
		return out;
	}
}
The point is that in the child class, super.execute () is done and the return value is expected.
JUnit test class
@RunWith(PowerMockRunner.class)
@PrepareForTest({Parent.class})//Specify parent
public class MockSuperTest {
	//Tested class
	@InjectMocks
	private Child child;
	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}
	@Test
	public void testExecute1() {
		//Input data preparation
		InputDto input = new InputDto();
		input.setText("hello");
		OutputDto result = new OutputDto();
		result.setText("hello updated in Child.");
		try {
			Method method = child.getClass().getMethod("execute", InputDto.class);
			PowerMockito.replace(method).with(
				new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						System.out.println("replaced execute()!!");
						return result;
					}
				});
		} catch (Exception e) {
			e.printStackTrace();
			fail();
		}
		OutputDto testOut = child.execute(input);
		assertEquals(result.getText(), testOut.getText());
	}
}
When you run JUnit above,
Child#execute()
replaced execute()!!
Then, after calling ʻexecute ()of the child class,super.execute ()is replaced with the content specified byPowerMockito.replace ()`.
By the way,
@PrepareForTest({Child.class})//Specify a child
public class MockSuperTest {
If you specify the place in the child class, the result will be
replaced execute()!!
Directly change ʻexecute ()` of the neighboring child class. Of course if you run it normally
Child#execute()
Parent#execute()
Is the expected value.
that's all.
Recommended Posts