I have a controller
@RestController
public class Create {
@Autowired
private ComponentThatDoesSomething something;
@RequestMapping("/greeting")
public String call() {
something.updateCounter();
return "Hello World " + something.getCounter();
}
}
I have a component for that controller
@Component
public class ComponentThatDoesSomething {
private int counter = 0;
public void updateCounter () {
counter++;
}
public int getCounter() {
return counter;
}
}
I also have a test for my controller.
@RunWith(SpringRunner.class)
@SpringBootTest
public class ForumsApplicationTests {
@Test
public void contextLoads() {
Create subject = new Create();
subject.call();
subject.call();
assertEquals(subject.call(), "Hello World 2");
}
}
The test fails when the controller calls something.updateCounter()
. I get a NullPointerException
. While I understand it's possible to add @Autowired
to a constructor I would like to know if there is anyway to do this with an @Autowired
field. How do I make sure the @Autowired
field annotation works in my test?