I have a spring application and I want to create a unitary test on a controller like this one. The problem is that the Wrapper class is a private inner class, so Wrapper is not understood in the test. Is it possible to mock it with Mockito without changing the controller class. I can use prepareData() to get an instance of the object, but I don’t know if this could be used to mock that object.
Thanks
@Controller
public class Controller {
private class Wrapper {
private Object1 field1;
private Object2 field2;
private Object1 method1(){
...
}
private Object2 method1(){
...
}
}
@ModelAttribute("data")
public Wrapper prepareData() {
return new Wrapper ();
}
public String save(@ModelAttribute("data") Wrapper wrapper, BindingResult result, Model model){
...
}
}
So in my test I would have something like this
@Test
public void usernameEmpty(){
BindingResult result = Mockito.mock(BindingResult.class);
Model model = Mockito.mock(Model.class);
Wrapper data = //how to mock it
when(data.method1()).then(new Foo1());
when(data.method2()).then(new Foo2());
String returned = controller.save(data, result, model);
....
}
Your test is on methods, but it tests the whole class behavior. If your inner class is private then its an implementation detail. Something that the test shouldn’t know. It there’s a lot of behaviour in that inner-class and you want to test it independently maybe you should make it public and separate from this class.
Maybe you think: but then… it’s a lot of code to test (a very big indivisible thing), can’t I test something smaller? Well… yes. Test Driven Development mandates to make a minimal implementation and add more code only if you add more tests. So you start with some test and minimal implementation and evolve both of them until the tests have all the specification and the code all the implementation.
So don’t worry about private inner classes. Test your class contract!