Skip to content

Instantly share code, notes, and snippets.

@larsthorup
Created April 15, 2012 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsthorup/2394566 to your computer and use it in GitHub Desktop.
Save larsthorup/2394566 to your computer and use it in GitHub Desktop.
Place your test data next to the test code.
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