我正在研究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贡献一些代码来启用这种行为更容易吗?
我在这里发现了类似的问题,Reusing NSpec specifications,但我想保留lambda-expression语法(没有继承),以便在一个地方看到所有规范。
发布于 2013-01-31 18:14:08
很抱歉,这两个星期都没有回答,但我只是通过提取如下方法来解决这个问题
void ItShouldRequestExactly(int n)
{
it["should do " + n + " request"] = () => sendTimes.should_be(n);
}在大多数情况下,这对我来说已经足够干了。然而,当你传入在规范执行时实际初始化的对象时,你会遇到一些微妙的问题,但对于这个简单的例子来说,它非常适合。遗憾的是,我没有看到另一种将这样的混合断言注入到上下文中的方法。
https://stackoverflow.com/questions/14368245
复制相似问题