Petrica3696
Petrica3696

Reputation: 3

Mocking Java Spring Test - NullPointerException

I am new to testing with mocks and I am trying to test a method on a controller, however I get NullPointerException. Here is my controller method:

    //CREATE MARK
@RequestMapping(value = "/marks", method = RequestMethod.POST)
public void createMark(@RequestBody MarkDTO markDTO) {
    markService.createMark(markDTO);
}

Here is my service:

public interface MarkService {

Page<MarkDTO> getMarks(Pageable pageable);
MarkDTO getMark(Integer id);

void createMark(MarkDTO markDTO);
void updateMark(Integer id, Mark mark);
void deleteMark(Integer id);

}

And this is my test:

public class MarkControllerTest {

@Autowired
private WebApplicationContext ctx;

@Mock
private MarkService markService;

private MockMvc mockMvc;

@Before
public void setup(){

}

@Test
public void createMark() throws Exception {


   //doNothing().when(markService.createMark(markDTO));
    mockMvc.perform(post("/marks")
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\n" +
                    "  \"id\": 1,\n" +
                    "  \"id_profesor\": 2,\n" +
                    "  \"valoare\": 10,\n" +
                    "  \"data_notare\": \"2017-05-29\"\n" +
                    "}"));
}

}

If I un-comment the doNothing line, I get an error, something like T Stubbed can't be applied to void.

I am not sure how to mock my service, however I get this error:

java.lang.NullPointerException at com.fiivirtualcatalog.modules.homework.controllers.MarkControllerTest.createMark(MarkControllerTest.java:66)

Any idea where I migh t be going wrong?

Upvotes: 0

Views: 116

Answers (1)

arsen_adzhiametov
arsen_adzhiametov

Reputation: 696

Firstly, do not foget to declare controller you whant to test inside test class, and call this inside your @Before method:

 MockitoAnnotations.initMocks(this);
 this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

And second one, to prevent error of mocking markService method call you need to use below code:

doNothing().when(markService).createMark(markDTO);

instead of:

doNothing().when(markService.createMark(markDTO));

Upvotes: 2

Related Questions