27 Ekim 2022 Perşembe

MockServer - Sunucudan Gelen Cevap Gibidir

Giriş
MockServer yerine bir diğer seçenek WireMock
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.mock-server</groupId>
  <artifactId>mockserver-netty</artifactId>
  <version>5.13.0</version>
</dependency>
<dependency>
  <groupId>org.mock-server</groupId>
  <artifactId>mockserver-client-java</artifactId>
  <version>5.13.0</version>
</dependency>
Örnek
Şu satırı dahil ederiz
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.mock-server</groupId>
  <artifactId>mockserver-spring-test-listener-no-dependencies</artifactId>
  <version>5.14.0</version>
</dependency>
MockServerClient Sınıfı
Şu satırı dahil ederiz
import org.mockserver.client.MockServerClient;
when metodu
Şöyle yaparız
import static org.hamcrest.Matchers.is;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.nimbusds.jose.jwk.RSAKey;
import com.pohorelov.medium.configuration.SecurityConfiguration;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.springtest.MockServerTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

@ActiveProfiles("test")
@MockServerTest
@WebMvcTest(controllers = BaseController.class)
class BaseControllerTest {

  private MockServerClient mockServerClient;

  @Autowired
  private MockMvc mockMvc;

  private static String jwks;
  private static String jwt;

  @BeforeAll
  public static void setUp() {
    final var keyPair = generateKeyPair();
    jwks = generateJwksJson(keyPair);
    jwt = authorize(keyPair);
  }

  @BeforeEach
  public void setUpServer() {
    mockServerClient
        .when(
            request()
                .withMethod("GET")
                .withPath("/auth/realms/test-realm/protocol/openid-connect/certs"))
        .respond(response().withStatusCode(200).withBody(jwks));
  }
 

  @SneakyThrows
  private static KeyPair generateKeyPair() {
    final var keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(1024);
    return keyGenerator.generateKeyPair();
  }

  private static String generateJwksJson(KeyPair keyPair) {
    final var rsaKey = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()).build();
    final var jwk =
        Map.of(
            "kid", "test",
            "kty", "RSA",
            "alg", "RS256",
            "n", rsaKey.getModulus().toString(),
            "e", rsaKey.getPublicExponent().toString());
    final var responseSet = Map.of("keys", List.of(jwk));
    final var jsonObj = new JSONObject(responseSet);
    return jsonObj.toString();
  }

  @SneakyThrows
  private static String authorize(KeyPair keyPair) {
    return Jwts.builder()
        .setHeaderParam("kid", "test")
        .signWith(SignatureAlgorithm.RS256, keyPair.getPrivate())
        .claim("accountId", "1")
        .claim("permissions", "base-controller-read")
        .setExpiration(new Date(System.currentTimeMillis() + 5 * 60 * 1000))
        .compact();
  }

}
Test kodu için şöyle yaparız
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;


@SneakyThrows
@Test
void shouldReturnAccountData() {
  final var headers = new HttpHeaders();
  headers.setBearerAuth(jwt);
  mockMvc.perform(get("/accounts/1").headers(headers))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.accountName", is("Oleksandr Pohorelov")));
}

@SneakyThrows
@Test
void shouldReturnForbidden() {
  final var headers = new HttpHeaders();
  headers.setBearerAuth(jwt);
  mockMvc.perform(get("/accounts/2").headers(headers))
    .andExpect(status().isForbidden())
    .andExpect(jsonPath("$.errorMessage",
      is("Search account id is not associated with current user")));
}
verify metodu
Örnek
Şöyle yaparız. Böylece MockServer "http://localhost:1080/api/helloWorld" adresini dinler
public class MockServerConfig {
  private static final Integer MOCK_SERVER_PORT = 1080;
  private final ClientAndServer clientAndServer;
  private final MockServerClient mockServerClient = new MockServerClient("localhost", 
    MOCK_SERVER_PORT);

  MockServerConfig() {
    this.clientAndServer = ClientAndServer.startClientAndServer(MOCK_SERVER_PORT);
  }

  public void registerHelloWorldEndpoint() {
    mockServerClient
      .when(
        request()
          .withMethod("GET")
          .withPath("/api/helloWorld"),
        exactly(1)
      )
      .respond(
        response()
          .withStatusCode(200)
          .withBody("Mocked Response!!!!!!")
          .withDelay(TimeUnit.SECONDS, 1)
      );
  }

  public void verifyHelloWorldEndpoint() {
    mockServerClient.verify(
      request()
        .withMethod("GET")
        .withPath("/api/helloWorld"),
      VerificationTimes.exactly(1)
    );
  }

  public void stopServer() {
    clientAndServer.stop();
  }
}
Test içinde kullanmak için şöyle yaparız
@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DemoControllerE2ETest {
  
  private MockServerConfig mockServerConfig;
  @BeforeAll
  public void startServer() {
    mockServerConfig = new MockServerConfig();
    mockServerConfig.registerHelloWorldEndpoint();
  }
  @AfterEach
  public void tearDown() {
    mockServerConfig.verifyHelloWorldEndpoint();
  }
  @AfterAll
  public void tearDown() {
    mockServerConfig.stopServer();
  }
  ...
}


Hiç yorum yok:

Yorum Gönder