2

I am writing some contract tests and I am trying to mock my controller in order to test the wanted method. My method should only return status code 200, so not an object, and I do not know how to write this with Mono or Flux and I get an error because of that.

I tried something like this, but it does not work:

Mono<Integer> response = Mono.just(Response.SC_OK);
when(orchestration.paymentReceived(purchase)).thenReturn(response);

How should I write my "when" part in order to verify it returns status code 200?

Maria1995
  • 439
  • 1
  • 5
  • 21
  • You need to write a test with WebTestClient.bindToController. This way you will be sure what status is retuned after method call. Pure JUnit tests do not cover this. https://docs.spring.io/spring/docs/current/spring-framework-reference/pdf/testing-webtestclient.pdf – Beri Jul 14 '20 at 15:29

1 Answers1

2

In order to check response status code you will need to write a more complicated test, using WebTestClient. Like so:

Service service = Mockito.mock(Service.class);
WebTestClient client = WebTestClient.bindToController(new TestController(service)).build();

Now you are able to test:

  • serialization to JSON or other types
  • content type
  • response code
  • path to your method
  • invoked method (POST,GET,DELETE, etc)

Unit tests do not cover above topics.

// init mocks
when(service.getPersons(anyInt())).thenReturn(Mono.just(person));    

// execute rest resource
client.get() // invoked method
  .uri("/persons/1") // requested path
  .accept(MediaType.APPLICATION_JSON)
  .exchange()
  .expectStatus().isOk() // response code
  .expectHeader().contentType(MediaType.APPLICATION_JSON)
  .expectBody()
  .jsonPath("$.firstName").isEqualTo(person.getFirstName())
  .jsonPath("$.lastName").isEqualTo(person.getLastName())
  

// verify you have called your expected methods
verify(service).getPerson(1);

You can find more examples here. Above test is also does not require Spring context, can work with mock services.

Beri
  • 11,470
  • 4
  • 35
  • 57