Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/test/java/hello/ApplicationContextLoadTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package hello;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.client.RestTemplate;

import hello.controller.GreetingController;
import hello.controller.HelloController;
import hello.controller.TopicController;
import hello.service.TopicService;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Starts the whole application context, including the {@link org.springframework.boot.CommandLineRunner}
* on {@link Application}. The runner contacts a demo quote service that no longer exists; the resulting
* WARN must not fail startup, so reaching the assertions below is itself part of what is being verified.
*/
@SpringBootTest
class ApplicationContextLoadTest {

@Autowired
private ApplicationContext context;

@Test
void contextLoads() {
assertThat(context).isNotNull();
}

@Test
void exposesTheExpectedBeans() {
assertThat(context.getBean(TopicService.class)).isNotNull();
assertThat(context.getBean(TopicController.class)).isNotNull();
assertThat(context.getBean(HelloController.class)).isNotNull();
assertThat(context.getBean(GreetingController.class)).isNotNull();
assertThat(context.getBean(RestTemplate.class)).isNotNull();
assertThat(context.getBean(JdbcTemplate.class)).isNotNull();
}

@Test
void commandLineRunnerPopulatedTheCustomersTable() {
Integer count = context.getBean(JdbcTemplate.class)
.queryForObject("SELECT COUNT(*) FROM customers", Integer.class);
assertThat(count).isEqualTo(4);
}
}
61 changes: 61 additions & 0 deletions src/test/java/hello/controller/GreetingControllerWebTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package hello.controller;

import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Pins the JSON contract of {@code /}: {@code {"id": <number>, "content": <string>}}.
*/
@SpringBootTest
@AutoConfigureMockMvc
class GreetingControllerWebTest {

@Autowired
private MockMvc mockMvc;

@Test
void greetsTheWorldByDefault() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.*", hasSize(2)))
.andExpect(jsonPath("$.id").isNumber())
.andExpect(jsonPath("$.content").value("Hello, World!"));
}

@Test
void greetsTheRequestedName() throws Exception {
mockMvc.perform(get("/").param("name", "Devin"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("Hello, Devin!"));
}

@Test
void everyGreetingGetsItsOwnId() throws Exception {
long first = greetingId();
long second = greetingId();

assertThat(second).isEqualTo(first + 1);
}

private long greetingId() throws Exception {
String json = mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
return JsonPath.parse(json).read("$.id", Long.class);
}
}
63 changes: 63 additions & 0 deletions src/test/java/hello/controller/HelloControllerWebTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package hello.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Covers the plain-text endpoints. {@code /topic/file/operation} walks the process working directory
* and reads {@code temp.txt} from it, so its exact output changes whenever a file is added to or
* removed from the repository; only the stable parts of the response are asserted.
*/
@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerWebTest {

@Autowired
private MockMvc mockMvc;

@Test
void datetimeEndpointRendersTheJavaTimeShowcase() throws Exception {
mockMvc.perform(get("/datetime"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Greetings from Spring Boot!")))
.andExpect(content().string(containsString("Datetime now is ")))
.andExpect(content().string(containsString("Is this a leap year ?")))
.andExpect(content().string(containsString("Default system zone id")))
.andExpect(content().string(containsString("Time in California: ")))
// "Datetime now is <ISO local date time>"
.andExpect(content().string(matchesRegex("(?s).*Datetime now is \\d{4}-\\d{2}-\\d{2}T[\\d:.]+.*")));
}

@Test
void stringOperationEndpointRendersTheStreamShowcase() throws Exception {
mockMvc.perform(get("/topic/string/operation"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Joining All String ID's with JOIN method: ")))
// The distinct-and-sorted characters and the ":"-split are both sorted, so they are
// stable even if another test has re-ordered the singleton's topic list.
.andExpect(content().string(containsString(":acgijnprstv")))
.andExpect(content().string(containsString("java:javascript")))
.andExpect(content().string(containsString("[spring]")));
}

@Test
void fileOperationEndpointRendersTheNioShowcase() throws Exception {
mockMvc.perform(get("/topic/file/operation"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Find all files in path and sort:")))
.andExpect(content().string(containsString("pom.xml")))
.andExpect(content().string(containsString("Read \"temp.txt\" file with stream functions")))
.andExpect(content().string(not(containsString("Error in IO"))))
.andExpect(content().string(not(containsString("IO exception"))));
}
}
125 changes: 125 additions & 0 deletions src/test/java/hello/controller/TopicControllerWebTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package hello.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* End-to-end coverage of the JSON contract of the topic endpoints.
*
* <p>{@code TopicService} is a singleton holding a mutable list, so anything that writes to it leaks
* into the next test. Rather than depending on test order, the two tests that mutate the list
* ({@code /topic} writes and the in-place sort performed by {@code /topic/sort}) drop the context
* afterwards with {@link DirtiesContext}; every other test can then assume the seeded state.
*
* <p>Assertions go through {@code jsonPath} rather than through model getters on purpose: the JSON
* field names are the actual contract and they survive the ongoing conversion of the models to records.
*/
@SpringBootTest
@AutoConfigureMockMvc
class TopicControllerWebTest {

@Autowired
private MockMvc mockMvc;

@Test
void getAllTopicsReturnsTheSeededTopics() throws Exception {
mockMvc.perform(get("/topic"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[*].id", containsInAnyOrder("spring", "java", "javascript")))
.andExpect(jsonPath("$[?(@.id=='spring')].subjectName", contains("Spring Framework")))
.andExpect(jsonPath("$[?(@.id=='spring')].subjectDescription", contains("Spring Framework Description")));
}

@Test
void aTopicSerialisesWithExactlyIdSubjectNameAndSubjectDescription() throws Exception {
mockMvc.perform(get("/topic/java"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(3)))
.andExpect(jsonPath("$.id").value("java"))
.andExpect(jsonPath("$.subjectName").value("Core Java"))
.andExpect(jsonPath("$.subjectDescription").value("Java Description"));
}

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
void supportsTheFullCreateReadUpdateDeleteLifecycle() throws Exception {
mockMvc.perform(post("/topic")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"id":"kotlin","subjectName":"Kotlin","subjectDescription":"Kotlin Description"}"""))
.andExpect(status().isOk());

mockMvc.perform(get("/topic"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(4)))
.andExpect(jsonPath("$[*].id", containsInAnyOrder("spring", "java", "javascript", "kotlin")));

mockMvc.perform(get("/topic/kotlin"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subjectName").value("Kotlin"))
.andExpect(jsonPath("$.subjectDescription").value("Kotlin Description"));

mockMvc.perform(put("/topic/kotlin")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"id":"kotlin","subjectName":"Kotlin Updated","subjectDescription":"Updated Description"}"""))
.andExpect(status().isOk());

mockMvc.perform(get("/topic/kotlin"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subjectName").value("Kotlin Updated"))
.andExpect(jsonPath("$.subjectDescription").value("Updated Description"));

mockMvc.perform(delete("/topic/kotlin"))
.andExpect(status().isOk());

mockMvc.perform(get("/topic"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[*].id", not(hasItem("kotlin"))));
}

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
void sortEndpointReturnsTopicsOrderedById() throws Exception {
mockMvc.perform(get("/topic/sort"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[*].id", contains("java", "javascript", "spring")));
}

@Test
void minimumLengthEndpointFiltersOnIdLength() throws Exception {
mockMvc.perform(get("/topic/minimum/length/4"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[*].id", containsInAnyOrder("spring", "javascript")));

mockMvc.perform(get("/topic/minimum/length/6"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[*].id", contains("javascript")));

mockMvc.perform(get("/topic/minimum/length/20"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(0)));
}
}
54 changes: 54 additions & 0 deletions src/test/java/hello/controller/TopicNotFoundStatusTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package hello.controller;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Requesting an unknown topic id is the one place where the HTTP status carries real information, and
* MockMvc rethrows unhandled exceptions instead of running the error dispatch, so this one case is
* driven over a real connection.
*
* <p>{@code TopicService.getTopicWithId} calls {@code Optional.get()} on a miss, which throws
* {@link java.util.NoSuchElementException} and surfaces as HTTP 500. That is asserted here as the
* <em>current</em> behaviour; the disabled test below is the replacement for when a parallel change
* turns the miss into a proper 404.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TopicNotFoundStatusTest {

@Autowired
private TestRestTemplate restTemplate;

@Test
void unknownTopicIdCurrentlyReturnsInternalServerError() {
ResponseEntity<String> response = restTemplate.getForEntity("/topic/does-not-exist", String.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}

@Test
@Disabled("Enable, and delete unknownTopicIdCurrentlyReturnsInternalServerError, once an unknown id is a 404")
void unknownTopicIdShouldReturnNotFound() {
ResponseEntity<String> response = restTemplate.getForEntity("/topic/does-not-exist", String.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}

@Test
void knownTopicIdReturnsOkWithTheUnchangedJsonShape() {
ResponseEntity<String> response = restTemplate.getForEntity("/topic/spring", String.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody())
.contains("\"id\":\"spring\"")
.contains("\"subjectName\":\"Spring Framework\"")
.contains("\"subjectDescription\":\"Spring Framework Description\"");
}
}
Loading
Loading