我试图在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进行实际测试。
[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")。
发布于 2019-05-21 21:21:06
模拟静态方法(如SerialPort.GetPortNames )的方法是添加一个间接层。在您的情况下,最简单的方法是创建一个SerialPortList重载,该重载可以像这样接受一个Func<string[]>。
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;
}在你的单元测试中。
public void Test()
{
var portNames = new[] { "COM1" };
foo.SerialPortList(() => portNames);
}https://stackoverflow.com/questions/56246205
复制相似问题