0

I am trying to write a unit test for spring controller, the myService class is autowired in myController,I have mocked myService class but when I debug the code it is coming null

myService = null

I am not able to inject this service for my controller.

   @RunWith(MockitoJUnitRunner.class)
    public class TestManageDevices {

        private MockMvc mockMvc;

        @Mock
        MyService myService;

        @Before
        public void setUp() {
            mockMvc = MockMvcBuilders.standaloneSetup(new MyController())
                    .build();
        }

        @Test
        public void shouldPass() throws Exception {
            Mockito.doNothing().when(myService).someMethod(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            JobResponse jobResponse = JobResponse.builder().responseCode(0).build();
            jobResponse.requestObj = "mockedStringObject";

            RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/pathfortest")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .param("id", Mockito.anyString());

            MvcResult result = mockMvc.perform(requestBuilder).andReturn();


            System.out.println(result.getResponse().getContentAsString());

            MockHttpServletResponse response = result.getResponse();


            Assert.assertEquals(HttpStatus.CREATED.value(), response.getStatus());

        }

    }
Ravat Tailor
  • 1,193
  • 3
  • 20
  • 44

1 Answers1

2

You are newing up the controller manually with new MyController() in the setUp method, so dependencies are not being injected.

Create a variable of type controller

@InjectMocks
MyController myController;      

Use this when creating mockMVC instance in your setUp method as below:

mockMvc = MockMvcBuilders.standaloneSetup(myController).build();

This should work.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Vishnu300
  • 126
  • 2
  • 11