기본 콘텐츠로 건너뛰기

냉장고 가계부 프로젝트 17

fridge 프로젝트에서 FoodController 메서드들을 리팩토링하고, 전체삭제기능을 추가한다.
FoodControllerTests 클래스부터 작성한다.
    @Test
    public void deleteAll() throws Exception {
        doNothing().when(jpaFoodService).removeAll();
        URI uri = UriComponentsBuilder.fromUriString("/foods").build().toUri();
        mvc.perform(MockMvcRequestBuilders.delete(uri))
            .andExpect(status().isNoContent())
            .andExpect(content().string(""));
        verify(jpaFoodService, times(1)).removeAll();
    }

deleteAll 테스트 메서드는 전체삭제기능을 테스트한다. jpaFoodService Mock 객체에 removeAll 메서드를 호출하면 void 를 리턴하기때문에 doNothing mockito 메서드를 호출한다.
/foods URL을 DELETE 방식으로 호출하면 HttpStatus는 NoContent를 응답하고 ResponseBody 는 비어있다.
mock객체를 검증하면 jpaFoodService 의 removeAll 메서드가 1번 호출했음을 확인한다.

다음은 FoodController 구현부이다.
    @DeleteMapping
    public ResponseEntity<?> deleteAllFood() {
        jpaFoodService.removeAll();
        return ResponseEntity.noContent().build();
    }

@DeleteMapping 애너테이션을 선언하면 deleteAllFood 메서드가 HttpMethod.DELETE 방식으로 매핑되고, jpaFoodService.removeAll 메서드를 호출하고 noContent 를 리턴한다.

findById 메서드의 데이터가 존재하지 않을 경우 NoContent 를 리턴하도록 수정한다.
    @GetMapping("/{id}")
    public ResponseEntity<FoodResource> findById(@PathVariable final long id) {
        Food food = jpaFoodRepository.findOne(id);
        if(food == null) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(assembler.toResource(food));
    }

updateFood, deleteFood 두 메서드도 noContent를 리턴하는 부분이 중복되어 있어서 중복을 제거한다.
    @PutMapping("/{id}")
    public ResponseEntity<?> updateFood(@PathVariable final long id, @RequestBody final Food food) {
        if(jpaFoodRepository.findOne(id) != null) {
            jpaFoodService.save(food);
        }
        return ResponseEntity.noContent().build();
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteFood(@PathVariable final long id) {
        if(jpaFoodRepository.findOne(id) != null) {
            jpaFoodService.remove(id);
        }
        return ResponseEntity.noContent().build();
    }

ControllerBase 추상클래스에서 Selenium Chrome Web Driver 파일을 환경변수에 설정하는 부분을 조금 수정한다.
    @BeforeClass
    public static void openBrowser() {
        String home = System.getProperty("user.home");
        System.setProperty("webdriver.chrome.driver", home + "/Documents/chromedriver");
        browser = new ChromeDriver();
        browser.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

기존 소스코드는 내 로컬컴퓨터 home 디렉토리를 하드코딩했는데 변경된 부분은 환경변수에서 user.home 프로퍼티를 불러와서 파일경로를 설정해주고 있다. 가장 깔끔하게 경로를 설정하는것은 프로젝트 내에 웹드라이버 파일을 위치시키고 ClassPath로 호출하는 것이다. 차후에 정리한다.

ControllerBase 추상클래스에서 setUp 메서드를 init으로 이름을 변경하고 추상메서드 setUp을 선언하여 자식클래스들이 setUp메서드를 구현하도록 수정한다.
    @Before
    public void init() {
        BASE_URL = host + ":" + port;
        setUp();
    }
    
    protected abstract void setUp();

자식클래스에서 setUp 메서드는 테스트 실행전에 수행할 작업을 구현할 수 있다.

FoodControllerTests 클래스는 registerFood 테스트 메서드 하나로 모든 UI를 다 테스트하고 있다.
메서드의 내용이 길어질수록 가독성이 떨어지고 코드를 이해하기 힘들어지므로 메서드들을 추출하고 미흡한 검증은 추가로 진행하고 중복코드는 제거하는 작업을 진행한다.
public class FoodControllerTests extends ControllerBase {
    
    @Autowired
    private RestTemplate restTemplate;
    
    private static final String FOOD_API_URL = "http://localhost:8081";
    
    @Override
    protected void setUp() {
        restTemplate.delete(FOOD_API_URL + "/foods", Collections.emptyMap());
    }
    
    @Test
    public void findRegistrationFoodButtonAndClick() {
        browser.get(BASE_URL + "/foods");
        browser.findElement(By.id("btnRegistrationFood")).click();
        assertThat(browser.getCurrentUrl()).isEqualTo(BASE_URL + "/foods/add");
    }
    
    @Test
    public void fillInFoodRegisterFormAndSubmit() {
        browser.get(BASE_URL + "/foods/add");
        
        FoodCommand food = new FoodCommand("파스퇴르 우유 1.8L", 1, new Date());
        LocalDateTime expiryDate = LocalDateTime.ofInstant(food.getExpiryDate().toInstant(), ZoneId.systemDefault());
        
        WebElement nameElement = browser.findElement(By.name("name"));
        WebElement quantityElement = browser.findElement(By.name("quantity"));
        WebElement expiryDateElement = browser.findElement(By.name("expiryDate"));
        nameElement.sendKeys(food.getName());
        quantityElement.sendKeys(Integer.toString(food.getQuantity()));
        expiryDateElement.sendKeys(expiryDate.format(DateTimeFormatter.ofPattern("yyyy")));
        expiryDateElement.sendKeys(Keys.TAB);
        expiryDateElement.sendKeys(expiryDate.format(DateTimeFormatter.ofPattern("MMdd")));
        browser.findElementByTagName("form").submit();
        
        WebDriverWait wait = new WebDriverWait(browser, 10);
        wait.until(ExpectedConditions.alertIsPresent());
        
        Alert alert = browser.switchTo().alert();
        assertThat(alert.getText()).isEqualTo("식품을 저장했습니다.");
        alert.accept();
    }
    
    @Test
    public void clickAnchorTagFromFood() {
        FoodCommand food = new FoodCommand("파스퇴르 우유 1.8L", 1, new Date());
        Long id = registrationFood(food);
        
        browser.get(BASE_URL + "/foods");
        
        String viewPageUrl = BASE_URL + "/foods/" + id;
        
        List<WebElement> anchors = browser.findElementsByLinkText(food.getName());
        assertThat(anchors).filteredOn(new Condition<WebElement>() {
            @Override
            public boolean matches(WebElement element) {
                return element.getAttribute("href").equals(viewPageUrl);
            }
        });
        
        WebElement anchorTag = anchors.stream()
                .filter(element -> element.getAttribute("href").equals(viewPageUrl))
                .findAny()
                .orElse(null);
        
        anchorTag.click();
        
        assertThat(browser.getCurrentUrl()).isEqualTo(viewPageUrl);
    }
    
    private Long registrationFood(FoodCommand foodCommand) {
        ResponseEntity<FoodCommand> response = restTemplate.postForEntity(FOOD_API_URL + "/foods", foodCommand, FoodCommand.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        Long id = response.getBody().getId();
        assertThat(id).isPositive();
        return id;
    }
    
    @Test
    public void changeFoodNameAndSubmit() {
        FoodCommand food = new FoodCommand("파스퇴르 우유 1.8L", 1, new Date());
        Long id = registrationFood(food);
        
        browser.get(BASE_URL + "/foods/" + id);
        
        String changeName = "코카콜라 500mL";
        WebElement nameElement = browser.findElement(By.name("name"));
        nameElement.clear();
        nameElement.sendKeys(changeName);
        browser.findElementByTagName("form").submit();
        
        WebDriverWait wait = new WebDriverWait(browser, 10);
        wait.until(ExpectedConditions.alertIsPresent());
        
        Alert alert = browser.switchTo().alert();
        assertThat(alert.getText()).isEqualTo("식품을 저장했습니다.");
        alert.accept();
        
        browser.get(BASE_URL + "/foods/" + id);
        assertThat(browser.findElement(By.name("name")).getAttribute("value")).isEqualTo(changeName);
    }
    
    @Test
    public void clickDeleteFoodButton() {
        FoodCommand food = new FoodCommand("파스퇴르 우유 1.8L", 1, new Date());
        Long id = registrationFood(food);
        
        browser.get(BASE_URL + "/foods/" + id);
        
        WebElement deleteBtn = browser.findElement(By.linkText("삭제"));
        assertThat(deleteBtn.getAttribute("href")).isEqualTo(BASE_URL + "/foods/delete/" + id);
        deleteBtn.click();
        
        WebDriverWait wait = new WebDriverWait(browser, 10);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = browser.switchTo().alert();
        assertThat(alert.getText()).isEqualTo("식품을 삭제했습니다.");
        alert.accept();
        
        ResponseEntity<FoodCommand> response = restTemplate.getForEntity(FOOD_API_URL + "/foods/" + id, FoodCommand.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
    }
    
}

RestTemplate을 선언해서 데이터를 삭제하거나 추가하는 작업에 사용한다.
before 메서드는 restTemplate.delete 메서드로 Food 전체 삭제 컨트롤러를 호출한다. 모든 테스트 메서드가 수행하기 전에 실행되므로 테스트 데이터가 쌓이지 않는다.

findRegistrationFoodButtonAndClick 메서드는 foods View페이지에서 등록버튼을 찾고 클릭해서 페이지 이동한것을 검증하는 테스트 메서드이다.

fillInFoodRegisterFormAndSubmit 메서드는 food 등록폼 페이지에서 input 필드의 값을 채우고 submit해서 alert 메시지가 정상적으로 나타나는지 검증한다.

clickAnchorTagFromFood 메서드는 foods View페이지에서 registrationFood 메서드를 이용해서 새로 만든 Food의 id가 목록페이지에 존재하는지 검증하고 앵커태그를 클릭해서 상세페이지로 페이지 이동이 되는지 검증한다.

changeFoodNameAndSubmit 메서드는 registrationFood 메서드를 이용해서 새로 만든 Food의 수정페이지로 이동해서 name 필드의 값을 변경하고 submit해서 alert 메시지가 정상적으로 나타나는지 검증한다. 또한, 다시한번 페이지를 이동해서 name값이 실제로 변경되었는지 확인한다.

clickDeleteFoodButton 메서드는 registrationFood 메서드를 이용해서 새로 만든 Food의 수정페이지로 이동해서 삭제버튼을 찾고, 클릭해서 alert 메시지를 검증한다. 또한, 다시한번 삭제한 페이지로 접근해서 데이터가 존재하는지 검증한다.

거대하게 뭉쳐있던 메서드를 하나씩 메서드로 뜯어내자 좀 보기가 편해졌다. 완벽하지는 않지만 계속 손보면 조금은 더 나아질것이다.

리팩토링하고 테스트를 수행해서 문제가 없는지 확인한다.

이전글: 냉장고 가계부 프로젝트 16
다음글: 냉장고 가계부 프로젝트 18

이 블로그의 인기 게시물

냉장고 가계부 프로젝트 14

fridge-web 프로젝트에서 api 서버와 통신할때 URL을 매번 중복해서 입력하는 부분을 제거하기 위해 RestTemplate 빈 등록메서드를 수정한다. @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.rootUri("http://localhost:8081").build(); } builder에 rootUri 메서드를 호출해서 api 서버 url을 미리 설정하고 build해서 RestTemplate 객체를 반환하면 RestTemplate을 사용하는 부분에서는 root 다음 경로만 넘겨주면 된다. WebFoodController 클래스의 restTemplate 사용부분을 전부 수정한다. @GetMapping public String foods(Model model) { ResponseEntity<Resources<FoodCommand>> response = restTemplate.exchange("/foods", HttpMethod.GET, null, new ParameterizedTypeReference<Resources<FoodCommand>>() {}, Collections.emptyMap()); .... 다른 메서드들도 동일하게 수정한다. Food 클래스에서도 이제 더이상 사용하지 않는 Cloneable과 hashCode, equals 메서드를 정리한다. Guava 의존라이브러리도 다른곳에서는 사용하지 않으므로 정리한다. 식품에 대한 최소한의 기능은 구현하였다. 이번에는 냉장고 라는 개념을 모델링한다. 식품들이 들어가고 나가는 곳은 냉장고이기 때문에 냉장고라는...

냉장고 가계부 프로젝트 27

스프링 Data 에서 제공하는 @CreatedDate, @LastModifedDate 애너테이션을 이용해서 작성일자, 수정일자를 도메인객체가 생성되고, 수정될 때 관리될 수 있도록 한다. Spring Data를 쓰기 전에는 DB컬럼에 Date 타입의 등록일 컬럼을 추가하고 DEFAULT 값으로 SYSDATE 를 줘서 DB에 Insert 되는 시간에 등록일자 컬럼이 채워지는 방식을 사용했었고, Update 쿼리가 실행될때 수정일자 컬럼에 SYSDATE를 직접 Update 해주는 방식을 자주 썼다. 그 뿐만아니라, 등록일자와 더불어 등록한 사용자(ex: registerUser)를 식별하는 식별키(ex: userId, username ...) 를 Insert 쿼리가 실행될때 등록해주고, 수정한 사용자(ex: modifedUser)를 Update 쿼리에 설정하는 방식은 차후에 있을지도 모를 일에 대비해서 늘 반복해서 작업했다. 스프링 Data 에서 제공하는 JPA Audit 기능은 이런 코드의 반복을 줄여준다. 사용자 같은 경우 객체로 넘기면 객체의 식별자가 담긴다. 등록시간은 날짜형 타입이다. public class Blog { @CreatedBy private User user; @CreatedDate private LocalDateTime creadtedDate; } Blog 클래스의 User 객체는 @CreatedBy 애너테이션으로 선언되서 등록한 사용자를 나타내는 컬럼에 값을 입력할것이다. createdDate 필드는 도메인객체가 영속성 저장소에 반영되는 시간을 나타낸다. Fridge, Food 클래스에 등록일, 수정일만 먼저 적용한다. 두 클래스에 createdDate, lastModifedDate 멤버변수를 선언한다. @Data @NoArgsConstructor @Entity @EntityListeners(AuditingEntityListener.class) public class Fridge { ...

냉장고 가계부 프로젝트 10

API 가 어느정도 준비되었으므로, UI를 만든다. 별도의 프로젝트로 구성해서 API를 호출하는 방식으로 구성한다. 프로젝트명은 fridge-web이라고 정한다. 냉장고 가계부 프로젝트 1 을 참고한다. 새 프로젝트에서는 Dependencies를 Web, Thymeleaf, DevTools 세개를 체크한다. 프로젝트가 준비되면, pom.xml 파일을 연다. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <gro...