2011-11-24 68 views
0

我将从Web应用程序获取xml,如下所示。xml validate value null

<note> 
<to>Tove</to> 
<from>J</from> 
<heading>Reminder</heading> 
<body>Some Message</body> 
</note> 

我将能够断言,如果在标签中的值与此类似

<note> 
<to></to> 
<from>J</from> 
<heading>Reminder</heading> 
<body>Some Message</body> 
</note> 

,我需要使用Java和JUnit去做空的东西。

+4

[你有什么尝试?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+0

你是如何解析这个XML?你正在创建一个对象吗? – mprabhat

+0

@TimofeyStolbov我喜欢:) +1 – mprabhat

回答

2

由于这是一个开放式问题,我会尝试给你一个简单的解决方案。

使用XStream来解析xml到对象和对象到xml。

您可以在10分钟内开始使用XStream,请阅读this

我的笔记类

public class Note { 
private String to = null; 
private String from = null; 
private String heading = null; 
private String body = null; 

public Note(String to, String from, String heading, String body) { 
    super(); 
    this.to = to; 
    this.from = from; 
    this.heading = heading; 
    this.body = body; 
} 

public String getTo() { 
    return to; 
} 

public void setTo(String to) { 
    this.to = to; 
} 

public String getFrom() { 
    return from; 
} 

public void setFrom(String from) { 
    this.from = from; 
} 

public String getHeading() { 
    return heading; 
} 

public void setHeading(String heading) { 
    this.heading = heading; 
} 

public String getBody() { 
    return body; 
} 

public void setBody(String body) { 
    this.body = body; 
} 

@Override 
public String toString() { 
    return new StringBuilder().append("To = ").append(this.getTo()) 
      .append(" ,From = ").append(this.getFrom()) 
      .append(" ,Heading = ").append(this.getHeading()) 
      .append(" ,Body = ").append(this.getBody()).toString(); 
} 

}

类:

一旦你创建你的对象说Note那么您可以在您的JUnit下面

assertNotNull(note.getTo()); 

示例代码说它将XML转换为对象和对象为XML

import com.thoughtworks.xstream.XStream; 
import com.thoughtworks.xstream.io.xml.DomDriver; 

public class TestXStream { 

public String getXMLFromObject(Note object) { 
    XStream xStream = new XStream(new DomDriver()); 
    return xStream.toXML(object); 
} 

public Note getNoteFromXML(String noteXML) { 
    XStream xStream = new XStream(new DomDriver()); 
    return (Note) xStream.fromXML(noteXML); 
} 

}

和样本JUnit测试案例:

import static org.junit.Assert.*; 

import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 


public class XStreamJunitTest { 

@Before 
public void setUp() throws Exception { 
} 

@After 
public void tearDown() throws Exception { 
} 

@Test 
public void test() { 
    Note note = new Note("TestTo", "TestFrom", "TestHeading", "TestBody"); 
    TestXStream testXStream = new TestXStream(); 
    note = testXStream.getNoteFromXML(testXStream.getXMLFromObject(note)); 
    assertNotNull(note.getBody()); 
} 

}

希望这有助于,并让你去。