public class Restaurant {
private Long id;
private String name;
private String address;
public Restaurant(String name) {
this.name = name;
}
public Restaurant(Long id, String name, String address) {
this.id = id;
this.address = address;
this.name = name;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getInformation() {
return name + " in " + address;
}
public long getId() {
return id;
}
}
Junit5
@SpringBootTest
class RestaurantTests {
@Test
public void creation() {
Restaurant restaurant = new Restaurant(1004L, "Bob zip", "Seoul");
assertEquals(1004L, restaurant.getId());
assertEquals("Bob zip", restaurant.getName());
assertEquals("Seoul", restaurant.getAddress());
}
@Test
public void information() {
Restaurant restaurant = new Restaurant(1004L, "Bob zip", "Seoul");
assertEquals("Bob zip in Seoul", restaurant.getInformation());
}
}
@RestController
public class RestaurantController {
@GetMapping("/restaurant")
public List<Restaurant> list() {
List<Restaurant> restaurants = new ArrayList<>();
Restaurant restaurant = new Restaurant(1004L, "Bob zip", "Seoul");
restaurants.add(restaurant);
return restaurants;
}
@GetMapping("/restaurant/{id}")
public Restaurant detail(@PathVariable Long id) {
List<Restaurant> restaurants = new ArrayList<>();
restaurants.add(new Restaurant(1004L, "Bob zip", "Seoul"));
restaurants.add(new Restaurant(2020L, "Cyber Food", "Seoul"));
Restaurant restaurant = restaurants.stream()
.filter(r -> r.getId()==id)
.findFirst()
.orElse(null);
return restaurant;
}
}
Junit
@ExtendWith(SpringExtension.class)
@WebMvcTest(RestaurantController.class)
class RestaurantControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void list() throws Exception {
mvc.perform(get("/restaurant"))
.andExpect(status().isOk())
.andExpect(content().string(
containsString("\"id\":1004")
))
.andExpect(content().string(
containsString("\"name\":\"Bob zip\"")
));
}
@Test
public void detail() throws Exception {
mvc.perform(get("/restaurant/1004"))
.andExpect(status().isOk())
.andExpect(content().string(
containsString("\"id\":1004")
))
.andExpect(content().string(
containsString("\"name\":\"Bob zip\"")
));
mvc.perform(get("/restaurant/2020"))
.andExpect(status().isOk())
.andExpect(content().string(
containsString("\"id\":2020")
))
.andExpect(content().string(
containsString("\"name\":\"Cyber Food\"")
));
}
}