另一种方法是将 IWebRequestCreate 方法传递给构造函数。
public HTTPRequestFactory(IWebRequestCreate create)
{
_IWebRequestCreate = create;
}
public HTTPRequestFactory()
{
//Do nothing this is the real constructor, above is just for testing.
}
public WebRequest Create(String uri)
{
Uri _uri = new Uri("http://"+this.address+uri);
request = (HttpWebRequest)this.Create(_uri);
return request;
}
public WebRequest Create(Uri uri)
if (null == _IWebRequestCreate)
{
//use the real one
request = WebRequest.Create(uri);
}
else
{
//testing so use test one
request = _IWebRequestCreate.Create(uri);
}
return request;
}
然后,您可以使用标准测试来确认它是否按您的意愿被调用。
[Test]
public void NewwebrequestCreatesWebRequest()
{
var mockCreate = new Mock<IWebRequestCreate>();
mockCreate.Setup(x => x.Create(It.IsAny<Uri>()));
HTTPRequestFactory webrequest = new HTTPRequestFactory(mockCreate.Object);
HttpWebRequest request = (HttpWebRequest)webrequest.Create(testURI);
mockCreate.VerifyAll();
}
[Test]
public void webrequestUsesAddressProperty()
{
var mockCreate = new Mock<IWebRequestCreate>();
string IP = "10.99.99.99";
Uri expected = new Uri("http://10.99.99.99/services");
mockCreate.Setup(x => x.Create(expected));
HTTPRequestFactory webrequest = new HTTPRequestFactory(mockCreate.Object);
webrequest.address = IP;
HttpWebRequest request = (HttpWebRequest)webrequest.Create(testURI);
mockCreate.VerifyAll();
}
使用两个 Create 函数的原因是您要传入一个字符串 Create(string),而 IWebRequestCreate 需要一个 Create(Uri)。
已编辑,因为标准依赖注入不适用于 IWebRequestCreate。标准模式是使用接口实例化一个对象并通过构造函数将其传入。由于无法使用构造函数创建 WebRequest 并且无法实例化接口,因此上述逻辑可以解决此问题。