繁体   English   中英

存根Web服务器进行集成测试

[英]stub webserver for integration testing

我有一些集成测试,我想验证针对第三个[arty]网络服务器的某些要求。 我当时在想用存根服务器代替第三方服务器,该存根服务器仅记录对它的调用。 调用不需要成功,但是我确实需要记录所发出的请求(主要是路径+查询字符串)。

我当时正在考虑仅使用IIS。 我可以1)设置一个空站点,2)修改系统的主机文件以将请求重定向到该站点3)在每次测试结束时解析日志文件。

这是有问题的,因为对于IIS,不会立即将日志文件写入日志文件,而是将文件连续写入。 我需要找到文件,在测试之前读取内容,在测试之后等待不确定的时间,读取更新内容,等等。

有人可以想到一种更简单的方法吗?

您可以使用System.Net.HttpListener( MSDN LINK )。

它用作嵌入式WebServer,这意味着您甚至可以在不分析日志文件的情况下即时检查访问。

我最近在代码中使用的一个类:

class Listener
{
    private HttpListener listener = null;

    public event EventHandler CommandReceived;

    public Listener()
    {
        this.listener = new HttpListener();
        this.listener.Prefixes.Add("http://localhost:12345/");
    }

    public void ContextReceived(IAsyncResult result)
    {
        if (!this.listener.IsListening)
        {
            return;
        }
        HttpListenerContext context = this.listener.EndGetContext(result);
        this.listener.BeginGetContext(this.ContextReceived, this.listener);

        if (context != null)
        {
            EventHandler handler = this.CommandReceived;
            handler(context, new EventArgs());
        }
    }

    public void Start()
    {
        this.listener.Start();
        this.listener.BeginGetContext(this.ContextReceived, this.listener);
    }

    public void Stop()
    {
        this.listener.Stop();
    }
}

是的,我认为您不需要整个Web服务器。 您无需测试HTTP。

什么需要测试的是你在发送和接收的基础数据结构。 因此,只需为此创建测试(即指出您可以根据期望的内容以及打算接收的内容等来验证生成的数据格式)。

测试数据,而不是协议(除非显而易见,协议是自定义的)。

在许多项目中,我都做了与此非常相似的事情。

您不想创建存根Web服务。 那只是添加不需要的依赖项。 我所做的是创建一个模仿Web服务API的接口。 然后,我创建了一个代理类,该类将在实时系统中调用Web服务。 为了进行测试,我使用RhinoMocks创建模拟类,这些类返回要测试的结果。 这对我来说非常有用,因为这样我就可以产生各种“意外”行为,这在实时系统中是不可能的。

public interface IServiceFacade {
    string Assignments();
}

public class ServiceFacade : IServiceFacade {
    private readonly Service _service;

    public ServiceFacade(Service service) {
        _service = service;
    }

    public string Assignments() {
        return _service.Assignments();
    }
}

然后我的测试代码包含以下内容:

        var serviceFacade = MockRepository.GenerateMock<IServiceFacade>();
        serviceFacade.Stub(sf => sf.Assignments()).Return("BLAH BLAH BLAH");

要么

        serviceFacade.Stub(sf => sf.Assignments()).Return(null);

要么

        serviceFacade.Stub(sf => sf.Assignments()).Throw(new Exception("Some exception"));

我发现这非常有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM