我正在研究 NSpec 框架。
这是我的例子。我为一个简单的 HttpRequester 类编写了规范:
using Moq;
using NSpec;
namespace FooBrowser.UnitTests.BDD
{
class HttpRequester_specification : nspec
{
private HttpRequester requester;
private string sentData;
private int sendTimes;
private readonly Mock<IConnection> connectionMock;
private string resource;
public HttpRequester_specification()
{
connectionMock = new Mock<IConnection>();
connectionMock
.Setup(x => x.Send(It.IsAny<string>()))
.Callback<string>(data =>
{
sendTimes++;
sentData = data;
});
}
void given_opened_connection_with_no_recent_sends()
{
before = () =>
{
sendTimes = 0;
};
context["when HttpRequester is constructed"] = () =>
{
before = () => requester = new HttpRequester(connectionMock.Object);
it["should not do any request"] = () => sendTimes.should_be(0);
context["when performing request"] = () =>
{
act = () => requester.Request(resource);
context["when resource is not specified"] = () =>
{
it["should do 1 request"] = () => sendTimes.should_be(1);
it["should send HTTP GET / HTTP/1.0"] = () => sentData.should_be("GET / HTTP/1.0");
};
context["when resource is index.html"] = () =>
{
before = () => resource = "index.html";
it["should do 1 request"] = () => sendTimes.should_be(1);
it["should send HTTP GET /index.html HTTP/1.0"] = () => sentData.should_be("GET /index.html HTTP/1.0");
};
};
};
}
}
}
如您所见[“应该做 1 个请求”] = () => sendTimes.should_be(1); 写了两次。
我尝试将其移至外部上下文,如下所示:
context["when performing request"] = () =>
{
act = () => requester.Request(resource);
context["when resource is not specified"] = () =>
{
it["should send HTTP GET / HTTP/1.0"] = () => sentData.should_be("GET / HTTP/1.0");
};
context["when resource is index.html"] = () =>
{
before = () => resource = "index.html";
it["should send HTTP GET /index.html HTTP/1.0"] = () => sentData.should_be("GET /index.html HTTP/1.0");
};
it["should do 1 request"] = () => sendTimes.should_be(1);
};
但这会导致它[“应该做 1 个请求”] = () => sendTimes.should_be(1); 检查一次外部上下文,而不是我想要的内部上下文。
那么,我可以以某种方式将其移至外部上下文吗?
还是更容易向 NSpec 贡献一些代码来启用这种行为?
我在这里找到了类似的问题重用 NSpec 规范,但我想保留 lambda 表达式语法(没有继承)以在 1 个地方查看所有规范。