Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrichardsz/971034dee3212f4e89dc540c78aa75d8 to your computer and use it in GitHub Desktop.
Save jrichardsz/971034dee3212f4e89dc540c78aa75d8 to your computer and use it in GitHub Desktop.
java unit test snippets

https://thepracticaldeveloper.com/guide-spring-boot-controller-tests/

package acme.ldap.controller.meta;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import test.AppBoot;
import test.TestHelper;

@SpringBootTest(classes = AppBoot.class)
public class HealthControllerTest {

  static {
    TestHelper.readEnvironmentVariablesFromEnvFile();
  }

  private MockMvc mockMvc;
  
  @InjectMocks
  private HealthController healthController;  
  
  @BeforeEach
  public void setup() {
      // We would need this line if we would not use the MockitoExtension
      // MockitoAnnotations.initMocks(this);
      // Here we can't use @AutoConfigureJsonTesters because there isn't a Spring context
      JacksonTester.initFields(this, new ObjectMapper());
      // MockMvc standalone approach
      mockMvc = MockMvcBuilders.standaloneSetup(healthController)
              .build();
  }  

  @Test
  public void shouldReturnTheUrl() throws Exception {

    MvcResult mvcResult = mockMvc
        .perform(
            MockMvcRequestBuilders.get("/v1/meta/health").contentType(MediaType.APPLICATION_JSON))
        .andReturn();
    int status = mvcResult.getResponse().getStatus();
    assertEquals(200, status);
    String content = mvcResult.getResponse().getContentAsString();
    int receivedValue = JsonPath.read(content, "$.code");
    assertEquals(200000, receivedValue);
    String message = JsonPath.read(content, "$.message");
    assertEquals("success", message);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment