Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

.net - Automatically Unit Test Example Code

My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments. eg.

/// <summary>Summary here</summary>
/// <example>Here is an example  <code>example code here</code> </example>
public void SomeFunction() 

We then use Sandcastle and build the help files we need (chm and an online website).

It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.

Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest using a special bit of markup in your XML which says, "Grab the code sample from this place". It would refer to a normal C# file which can be run with unit tests. To take your example, you might have:

/// <summary>Summary here</summary>
/// <example>Here is an example
/// <code>!!sourcefile:SomeClassTest.cs#SomeFunction!!</code></example>
public void SomeFunction()

Your unit tests run as normal, and then insert a build step between "create XML" and "run Sandcastle" you'd replace each "file token" with the appropriate contents. There may even be hooks you could put into Sandcastle to do this at doc generation time - I don't know enough about Sandcastle to know for sure.

It's ugly to invent your own markup of course, but it should work.

Of course, this assumes that the code examples are easily unit testable - some may not be (if they're dealing with resources etc). At least you'd know it compiles though :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...