I am using spring 3 mvc/security frameworks.
I have created a Controller class that has a reference to a repository to load data from. The class is annotated with @Controller, the repository class is annotated with @Repository, and the instance of the respository is @Autowired.
However when I try to unit test, the autowired instance throws a null pointer exception.
Now, I understand that because it is autowired, it needs to be within the spring context to be picked up. But I feel that if I use @RunsWith() then it becomes an integration test. I would really like to separate the integration tests (using @RunsWith) and the unit test for this method. Any ideas on how I can get around this null pointer exception? Would just creating getter/setter methods on my controller class be okay?:
Repository class:
@Repository
public class Repository{
....
}
Controller class:
@Controller
public class Controller{
@Autowired
private Repository repo;
....
public String showView(){
repo.doSomething();
}
Test class:
public ControllerTest {
@Test
public shouldDoTestOfShowView(){
}
}
I personally tend to use @Simon’s approach, rather than exposing setters, although either approach is fine. Adding setters just for the sake of tests is a bit annoying, though.
An alternative is to use Spring’s
ReflectionTestUtilsclass to directly poke dependencies into the field using reflection, removing the need for special constructors and setters, e.g.Whether or not that still constitutes an “integration test” is your call (I don’t).