Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Test and NullPointerException

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

like image 230
Nicogo Avatar asked Sep 12 '26 10:09

Nicogo


1 Answers

The best way is to use the @MockBean annotation this way in your unit test and remove the mockito specific code from your test:

@MockBean
private DatabaseHandlerInt databaseHandler;

This way the mock will be injected by Spring, and you can use the usual Mockito.when() style to use your mock. Check out https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html for further information.

like image 82
Patrick Avatar answered Sep 14 '26 23:09

Patrick