mf2109
mf2109

Reputation: 11

Mock Spring Controller for unit testing

I'm trying to test a rest call that is a part of an mvc controller. My unit test is currently returning a 404 error code, instead of a 200 status code, which would determine that the request was sent successfully.

Here's the signature of my method that I'm trying to test:

@PreAuthorize("hasRole('ROLE_SSL_USER')")
@PostMapping(value = "/employee", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> postEmployee(HttpEntity<String> httpEntity, @RequestHeader("DB-Client-Id") String clientId,
        @RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}

Here's my unit test class:

public class ControllerTest {

  @InjectMocks
  private Controller aController;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();
  }

  @Test
  public void PostEmpTest() {

    try {
        this.mockMvc.perform(post("/employee")
                    .contentType(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}

Am I missing something from my perform() call that is resulting in the 404 bad request code?

Upvotes: 1

Views: 2367

Answers (1)

Bor Laze
Bor Laze

Reputation: 2516

I use for controller tests code like this

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
@AutoConfigureWebClient
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void entityTypes() throws Exception {
        String json = "...";
        mockMvc.perform(
                post("URL")
                        .contentType(APPLICATION_JSON_UTF8)
                        .content(json))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(APPLICATION_JSON_UTF8))
        ;
    }
}

Try it - I hope, it will help.

PS: also, I'm not sure, but it looks like you need add @RequestBody to your controller method declaration:

public ResponseEntity<Object> postEmployee(
    @RequestBody HttpEntity<String> httpEntity, 
    @RequestHeader("DB-Client-Id") String clientId,
    @RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}

Upvotes: 2

Related Questions