Skip to content

Instantly share code, notes, and snippets.

@cuongld2
Created October 30, 2020 02:42
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 cuongld2/e7032d5b4e75c6e2f4d149ac92379822 to your computer and use it in GitHub Desktop.
Save cuongld2/e7032d5b4e75c6e2f4d149ac92379822 to your computer and use it in GitHub Desktop.
Mock server test
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
properties = "blog-service.base-url:http://localhost:8082",
classes = BlogServiceClient.class)
@ContextConfiguration
public class UnitTest {
@Autowired
private BlogServiceClient blogServiceClient;
private static final String TITLE = "Testing";
@Test
public void test_blog_by_id() {
final Blog blog = blogServiceClient.getBlog("1");
assertThat(blog.getTitle()).isEqualTo(TITLE);
assertThat(blog.getId()).isEqualTo(1);
assertTrue(blog.getContent().matches(".*blog about.*"));
}
private static final int port = 8082;
private static ClientAndServer mockServer;
@BeforeClass
public static void startServer() {
mockServer = startClientAndServer(port);
createExpectationForInvalidAuth();
}
private static void createExpectationForInvalidAuth() {
new MockServerClient("127.0.0.1", port)
.when(
request()
.withMethod("GET")
.withPath("/blog/1")
.withHeader("\"Content-type\", \"application/json\"")
.withHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjdW9uZ2xkMiIsImV4cCI6MTYyMDIxMTE4NCwiaWF0IjoxNjAyMjExMTg0fQ.fdyeTWfkb4ng9asty_FHmKYu4Y1GWwysugqaYVCJVqC44MIW7yN3xkR3vI7q0zEaEmPnQs3SQokvYXZhzIu6Kw"),
exactly(1))
.respond(
response()
.withStatusCode(200)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400"))
.withBody("{\n" +
" \"id\": 1,\n" +
" \"title\": \"Testing\",\n" +
" \"content\": \"A blog about Testing\"\n" +
"}")
);
}
@AfterClass
public static void stopServer() {
mockServer.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment