I have to test some Spring controllers. I use mockito. But when I test a specific route, the linked function in controller can't use dependancy (NullPointerException) because the Autowired annotation don't work.
Below my code :
Test class :
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ClassTest {
@InjectMocks
private abcController abc;
private MockMvc mockMvc;
@Before
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(abc).build();
}
@Test
public void test1() throws Exception {
this.mockMvc.perform(get("/api/abc/"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]", is("a")))
.andExpect(jsonPath("$[1]", is("b")));
}
Controller (here happen the NullPointer exception databaseHandler is null) :
@RestController
@ComponentScan("com.example.*")
@Repository(value="abcController")
public class abcController extends BaseController {
@Autowired
@Qualifier("DatabaseHandler")
DatabaseHandlerInt databaseHandler;
@RequestMapping(value = "/api/abc", method = RequestMethod.GET)
public @ResponseBody ArrayList getContent() throws Exception {
// Null pointer happend here
return databaseHandler.example();
}
I think it's because the configuration is missing to the test class but i can't find a way to fix it.
Thanks