我正在开发一个使用CookComputing XML-RPC.net的应用程序。
我的问题是如何调用外部rpc方法的单元测试方法。
如果我们以这个网站为例:
//This is the XML rpc Proxy interface
[XmlRpcUrl("http://www.cookcomputing.com/xmlrpcsamples/RPC2.ashx")]
public interface IStateName : IXmlRpcProxy
{
[XmlRpcMethod("examples.getStateName")]
string GetStateName(int stateNumber);
}
public class MyStateNameService
{
public string GetStateName(int stateNumber)
{
IStateName proxy = XmlRpcProxyGen.Create<IStateName>();
return proxy.GetStateName(stateNumber);
}
}我们怎样才能有效地测试IStateName的结果而不实际命中http://www.cookcomputing.com/xmlrpcsamples/RPC2.ashx
我想一个好的开端应该是MyStateNameService上的构造函数--获取一个IStateName,并传递一个假的(或被嘲笑的?)IStateName上的例子..。
我感兴趣的是测试它的实际内容--例如,伪造端点的响应,并以某种方式返回响应,而不仅仅是验证GetStateName调用服务.
编辑
此外,我并不试图测试服务的内容,而且我的类对它做了什么。
例如,我们的反应是:
<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value><string>My State Name</string></value>
</param>
</params>
</methodResponse>我想要“伪造”这个回答--一些如何测试MyStateNameService.GetStateName是否真的返回了“我的国名”
发布于 2013-01-11 14:36:03
您的问题在于这里应用的Singleton模式。
XmlRpcProxyGen.Create<IStateName>();因此,您使用依赖注入(由构造器)的想法是一个好的开始。(您使用IoC容器吗?)
接下来是为IStateName服务创建一个模拟/假/Stub。这可以通过多种方式实现。
使用动态模拟系统可能会为您节省一些工作,但您需要了解它们的用法。
使用NUnit、NSubstitute和改进的MyStateNameService的经典AAA测试示例
class MyStateNameService
{
private readonly IStateName _remoteService;
public MyStateNameService(IStateName remoteService)
{
// We use ctor injection to denote the mandatory dependency on a IStateName service
_remoteService = remoteService;
}
public string GetStateName(int stateNumber)
{
if(stateNumber < 0) throw new ArgumentException("stateNumber");
// Do not use singletons, prefer injection of dependencies (may be IoC Container)
//IStateName proxy = XmlRpcProxyGen.Create<IStateName>();
return _remoteService.GetStateName(stateNumber);
}
}
[TestFixture] class MyStateNameServiceTests
{
[Test]
public void SomeTesting()
{
// Arrange
var mockService = Substitute.For<IStateName>();
mockService.GetStateName(0).Returns("state1");
mockService.GetStateName(1).Returns("state2");
var testSubject = new MyStateNameService(mockService);
// Act
var result = testSubject.GetStateName(0);
// Assert
Assert.AreEqual("state1", result);
// Act
result = testSubject.GetStateName(1);
// Assert
Assert.AreEqual("state2", result);
// Act/Assert
Assert.Throws<ArgumentException>(() => testSubject.GetStateName(-1));
mockService.DidNotReceive().GetStateName(-1);
/*
MyStateNameService does not do much things to test, so this is rather trivial.
Also different use cases of the testSubject should be their own tests ;)
*/
}
}https://stackoverflow.com/questions/14278194
复制相似问题