我正在尝试以 TDD 方式进行单元测试,因此我创建了一组我认为可以独立测试的接口。我不确定我是否成功,但我现在很确定是时候使用模拟框架了。我从示例中学习得最好,我认为非常精通的人可能能够快速将其翻译成其中之一(也许是 Moq 或 Rhino Mocks?那些是我找到的)。
单元测试:
[TestMethod]
public void RendererRendersEachWidgetByCallingBeginRenderThenEndRender()
{
// Mocks/Stubs
ISpace space = new MockSpace();
IWorld world = new MockWorld();
IWidget widget1 = new MockWidget("widget1");
IWidget widget2 = new MockWidget("widget2");
world.Add(widget1);
world.Add(widget2);
// Object under test
IRenderer target = new Renderer(world, space);
target.Render();
// verify BeginRender is called
Assert.IsTrue((space as MockSpace).results.Contains("Begin Render " + widget1.Id));
Assert.IsTrue((space as MockSpace).results.Contains("Begin Render " + widget2.Id));
// verify EndRender is called
Assert.IsTrue((space as MockSpace).results.Contains("End Render " + widget1.Id));
Assert.IsTrue((space as MockSpace).results.Contains("End Render " + widget2.Id));
// verify BeginRender is called before EndRender
var orderedResults = (space as MockSpace).results.Select((s, i) => Tuple.Create(i, s));
Assert.IsTrue(
(orderedResults.Single(x => x.Item2 == "Begin Render " + widget1.Id).Item1) <
(orderedResults.Single(x => x.Item2 == "End Render " + widget1.Id).Item1));
Assert.IsTrue(
(orderedResults.Single(x => x.Item2 == "Begin Render " + widget2.Id).Item1) <
(orderedResults.Single(x => x.Item2 == "End Render " + widget2.Id).Item1));
}