首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟/存根/shim SerialPort.GetPortNames()

如何模拟/存根/shim SerialPort.GetPortNames()
EN

Stack Overflow用户
提问于 2019-05-21 20:52:57
回答 1查看 429关注 0票数 0

我试图在ApiController中测试C#类,特别是使用SerialPort.GetPortNames()的函数。返回的内容取决于运行的机器,因此我希望能够以某种方式对其进行Shim/stub/模拟,以使其返回虚拟数据。

使用visual 2015,项目目标为.net 4.5.2,并使用Microsoft.VisualStudio.TestTools.UnitTesting

我认为微软假货能够完全满足我的需要,但我没有。

我在这里了解到Moq是毫无价值的,pose并不适用于项目所针对的.Net版本(4.5.2)。

我已经了解了prig,但是我不知道如何将它配置为datetime.now()以外的任何东西。

我不明白如何使用Smock进行实际测试。

代码语言:javascript
复制
        [HttpGet]
        [Route("PortList")]
        public HttpResponseMessage SerialPortList()
        {
            HttpResponseMessage response;
            try
            {
                List<string> Ports = new List<string>(SerialPort.GetPortNames());
                response = Request.CreateResponse(HttpStatusCode.OK, Ports);
            }
            catch (Exception ex)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
            return response;
        }

我想要能闪避(对吗?)来自SerialPort的静态方法,并让它返回串行端口的虚拟列表("COM1","COM2")。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-21 21:21:06

模拟静态方法(如SerialPort.GetPortNames )的方法是添加一个间接层。在您的情况下,最简单的方法是创建一个SerialPortList重载,该重载可以像这样接受一个Func<string[]>

代码语言:javascript
复制
public HttpResponseMessage SerialPortList()
{
    return SerialPortList(SerialPort.GetPortNames);
}

public HttpResponseMessage SerialPortList(Func<string[]> getPortNames)
{
    HttpResponseMessage response;
    try
    {
        List<string> Ports = new List<string>(getPortNames());
        response = Request.CreateResponse(HttpStatusCode.OK, Ports);
    }
    catch (Exception ex)
    {
        response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
    }
    return response;
}

在你的单元测试中。

代码语言:javascript
复制
public void Test()
{
    var portNames = new[] { "COM1" };
    foo.SerialPortList(() => portNames);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56246205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档