Place your test data next to the test code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Reflection; | |
using System.Xml; | |
using NUnit.Framework; | |
/// <summary> | |
/// Written in June 2006 by Lars Thorup, ZeaLake and Sune Gynthersen, BestBrains | |
/// Description here: http://www.zealake.com/2012/04/15/commentreader-place-your-test-data-next-to-the-test-code/ | |
/// </summary> | |
public class CommentReader | |
{ | |
private static XmlDocument generatedDocumentation = new XmlDocument(); | |
private static StackFrame callingMethodFrame; | |
public static string GetElement(string elementName) | |
{ | |
StackTrace stackTrace = new StackTrace(); | |
callingMethodFrame = stackTrace.GetFrame(1); | |
generatedDocumentation.Load(String.Format("{0}.xml", | |
Assembly.GetCallingAssembly().FullName.Split(',')[0])); | |
XmlNode node = generatedDocumentation.SelectSingleNode( | |
String.Format("doc/members/member[contains(@name, '{0}.{1}')]/{2}", | |
callingMethodFrame.GetMethod().DeclaringType.ToString(), | |
callingMethodFrame.GetMethod().Name, | |
elementName)); | |
if (node != null) | |
return node.InnerXml; | |
else | |
throw new ApplicationException(String.Format("Element '{0}' not found.", elementName)); | |
} | |
} | |
[TestFixture] | |
public class CommentReaderTest | |
{ | |
/// <sample> | |
/// <book> | |
/// <isbn>1234-1234</isbn> | |
/// <title>Code Complete</title> | |
/// </book> | |
/// </sample> | |
[Test] | |
public void TestXmlComment() | |
{ | |
string content = CommentReader.GetElement("sample"); | |
XmlDocument document = new XmlDocument(); | |
document.LoadXml(content); | |
Assert.AreEqual(@"Code Complete", document.SelectSingleNode("//book/title").InnerText); | |
} | |
/// <sample> | |
/// create table Orders ( id int, customer int ); | |
/// </sample> | |
[Test] | |
public void TestNonXmlComment() | |
{ | |
string content = CommentReader.GetElement("sample"); | |
Assert.AreEqual(@"create table Orders ( id int, customer int );", content.Trim()); | |
} | |
/// <sample> | |
/// link | |
/// </sample> | |
[Test] | |
public void TestMissingElement() | |
{ | |
try | |
{ | |
CommentReader.GetElement("missing"); | |
Assert.Fail(); | |
} | |
catch (ApplicationException ex) | |
{ | |
Assert.That(ex.Message, Is.EqualTo("Element 'missing' not found.")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment