SSH.Net.Sftp不能模拟不可重写的属性

6rvt4ljy  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(132)

使用单元测试,我需要绕过这段代码,到达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)
jjhzyzn0

jjhzyzn01#

通过创建我自己的类,只包含我使用的字段来管理它。它并不完美,因为从SSH.NET类重建整个功能容易出错。幸运的是,我只需要一些简单的属性。

public class CustomSftpFileAttributes
{
    public bool IsDirectory { get; set; }
}

Wrapper中的方法

var sftpFileAttributes = sftpClient.GetAttributes(fileName);
return new CustomSftpFileAttributes
{
    IsDirectory = sftpFileAttributes.IsDirectory,
};

相关问题