2016-09-13 3 views
0

어떻게 자바 객체에 대해 직접 XML의 노드를 비교 : 모음 등을에서 항목에 대한스프링 MVC 테스트 : 내가 함께 일하고

  • 스프링 MVC 테스트
  • Hamcrest

로 :

<collection> 
    <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="persona"> 
     <id>087</id> 
     <nombre>Leonardo</nombre> 
     <apellido>Jordan</apellido> 
     <fecha>1981-07-05</fecha> 
    </item> 
    .... 

다음 작품 :

.andExpect(xpath("collection/item[1]").exists()) 
.andExpect(xpath("collection/item[1]/*").nodeCount(is(4))) 
.andExpect(xpath("collection/item[1]/id").exists()) 
.andExpect(xpath("collection/item[1]/id").string(is("087"))) 
.andExpect(xpath("collection/item[1]/id").string(is(personasArray[0].getId()))) 
.andExpect(xpath("collection/item[1]/nombre").exists()) 
.andExpect(xpath("collection/item[1]/nombre").string(is("Leonardo"))) 
.andExpect(xpath("collection/item[1]/nombre").string(is(personasArray[0].getNombre()))) 
.andExpect(xpath("collection/item[1]/apellido").exists()) 
.andExpect(xpath("collection/item[1]/apellido").string(is("Jordan"))) 
.andExpect(xpath("collection/item[1]/apellido").string(is(personasArray[0].getApellido()))) 

객체가 아닌 각 객체가 아닌 객체와 직접 비교할 수 있는지 알고 싶으면 15에서 45 개의 필드가있는 엔티티를 고려하십시오. 그것을 사용하는 올바른 방법은 무엇인지 대표,

.andExpect(xpath("collection/item[1]/*").how(is(personasArray[0]))) 

how 부분을 참조하십시오

나는 이런 식으로 뭔가를해야합니다. path의 문자열 내용에 대해 동일한 고려 사항이 있습니다.

답변

1

이러한 주장을 수행 할 수 있습니다. 하지만 사용자 정의 ResultMatcher을 작성해야합니다. 나는 단위 테스트에서 간단한 비교를하기 위해 XML (노드)를 Java 객체로 변환하는 것이 좋은 생각이라고 생각하지 않는다. XML 네임 스페이스 해결 또는 올바르게 구현되지 않은 경우 Java hashCodeequals 계약과 관련된 문제가 발생할 수 있습니다.

대신 기술 또는 프로그래밍 언어의 세부 정보가 아닌 단위 테스트에 집중할 수있는 라이브러리를 사용해야합니다.

시험에 XMLUnit을 사용하는 것이 좋습니다. XMLUnit은 XML 비교를위한 Java 라이브러리입니다.

아래 예제는 XML 문서를 XMLUnit과 사용자 정의 ResultMatcher과 비교하는 것이 얼마나 쉬운 지 보여줍니다. 물론

import org.hamcrest.Matcher; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 
import org.springframework.test.context.junit4.SpringRunner; 
import org.springframework.test.web.servlet.MockMvc; 
import org.springframework.test.web.servlet.ResultMatcher; 
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
import org.xmlunit.builder.Input; 

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; 

@RunWith(SpringRunner.class) 
@WebMvcTest(XmlUnitDemoTests.XmlUnitDemo.class) 
public class XmlUnitDemoTests { 

    static final String XML_CONTENT = "<node1><node2 id=\"1\">text</node2></node1>"; 

    @Autowired 
    MockMvc mockMvc; 

    @Test 
    public void xmlUnit() throws Exception { 
     mockMvc.perform(get("/xml")) 
      .andExpect(xml(XML_CONTENT)); 
    } 

    static ResultMatcher xml(String bodyValue) { 
     return MockMvcResultMatchers.content().source(equalXml(bodyValue)); 
    } 

    static Matcher equalXml(String value) { 
     return isSimilarTo(Input.fromString(value).build()); 
    } 

    @SpringBootApplication 
    @RestController 
    static class XmlUnitDemo { 

     @RequestMapping(value = "xml", produces = "text/xml") 
     String xml() { 
      return XML_CONTENT; 
     } 
    } 

} 

, 당신은 클래스 패스에서 큰 XML 파일을로드하거나 비교를하기 전에 XPatch와 노드를 선택할 수 있습니다. 자세한 내용은 XMLUnit 설명서를 참조하십시오.

+0

귀하의 게시물 덕분에, 나는 당신의 소중한 제안을 점검 할 것입니다. 이제는 XML (노드)을 Java 객체로 변환하는 것이 좋다고 생각하지 않습니다. 단위 테스트에서 간단한 비교 만하면됩니다. 동의합니다. 물론 당신의 요지는 이해할 만하지만 원격 클라이언트에 OXM 기술이 있다고 가정해야합니다. 나는 Jackson과 함께'XML'과'JSON'을 위해 일한다. –

+0

당신은 당신의 프로젝트 설정에 더 잘 들어갔고, 당신은 올바른 결정을 내린 유일한 사람입니다. 나는 단지 내 의견과 경험을 당신과 공유하고 싶습니다. –

+0

나는 당신의 의견이 잘못되었다고 말하는 것이 아닙니다. 나는 동의하지만, 나의 요점은 '@ 시험'법전 편찬이다. 도메인 클래스에 리팩토링을 추가하거나 리팩터링 할 경우를 상상해보십시오. 나는 너의 제안을 시험 할 것이다. 그것은 가치있다. 다 괜찮아. 귀하의 게시물에 다시 한 번 감사드립니다. –

관련 문제