使用单元测试,我需要绕过这段代码,到达return IsFile;
行。变量client
是我自己的SSH.NetSftpClient的 Package 器,我可以模仿它。enum SftpCheckPathExistence
是我自己的自定义enum。
编码
SftpFileAttributes attrs = client.GetAttributes(fileName);
if (attrs.IsDirectory)
{
return SftpCheckPathExistence.IsDirectory;
}
return SftpCheckPathExistence.IsFile;
单元测试
clientMock.Setup(f => f.GetAttributes(It.IsAny<string>())).Returns(???);
问题是我不能模拟GetAttributes(filename)
的返回,它是类SftpFileAttributes
。
1.不写clientMock.Setup
SftpFileAttributes attrs = client.GetAttributes(fileName); // attrs is null
if (attrs.IsDirectory) // errors because its null
2.第一次尝试-返回示例化类
var sftpFileAttributes = new SftpFileAttributes(); // Class has no public constructor, this errors.
sftpFileAttributes.IsDirectory = false; // Property has private setter, this errors.
clientMock.Setup(f => f.GetAttributes(It.IsAny<string>())).Returns(sftpFileAttributes);
3.第二次尝试- mock SftpFileAttributes
var sftpFileAttributesMock = new Mock<SftpFileAttributes>();
sftpFileAttributesMock.SetupGet(f => f.IsDirectory).Returns(false);
// This errors because Moq creates a derived class as a mock and IsDirectory is not marked virtual to be overriden.
clientMock.Setup(f => f.GetAttributes(It.IsAny<string>())).Returns(sftpFileAttributes.Object);
错误代码:
System.NotSupportedException
HResult=0x80131515
Message=Unsupported expression: f => f.IsDirectory
Non-overridable members (here: SftpFileAttributes.get_IsDirectory) may not be used in setup / verification expressions.
Source=Moq
StackTrace:
at Moq.Guard.IsOverridable(MethodInfo method, Expression expression)
1条答案
按热度按时间jjhzyzn01#
通过创建我自己的类,只包含我使用的字段来管理它。它并不完美,因为从SSH.NET类重建整个功能容易出错。幸运的是,我只需要一些简单的属性。
Wrapper中的方法