I am trying to mock an inner method call of my test method
My class looks like this
public class App {
public Student getStudent() {
MyDAO dao = new MyDAO();
return dao.getStudentDetails();//getStudentDetails is a public
//non-static method in the DAO class
}
When I write the junit for the method getStudent(), is there a way in PowerMock to mock the line
dao.getStudentDetails();
or make the App class use a mock dao object during junit execution instead of the actual dao call which connects to the DB?
If you don't have access to Mockito, you can also use PowerMock to do the same purpose. For example you could do the following:
In order to get much out of the mocking framework, the MyDAO object has to be injected. You can either use something like Spring our Guice, or simply use a factory pattern to supply you with the DAO object. Then, in your unit test, you have a test factory to supply you with mock DAO objects instead of real ones. Then you can write code such as:
You can use the
whenNew()
method from PowerMock (see https://github.com/powermock/powermock/wiki/Mockito#how-to-mock-construction-of-new-objects)Full Test Case
I manufactured a simple Student class for this test case: