SftpClient 单元测试派生类和模拟基类 C#

SftpClient Unit test derived class and mock base class C#

提问人:Mihai Socaciu 提问时间:9/28/2023 最后编辑:Mihai Socaciu 更新时间:9/29/2023 访问量:58

问:

我有一个包装器.我想对这个包装器进行单元测试。Renci.SshNet.Sftp.SftpClient

我的包装器

public class MySftpClient: SftpClient, IMySftpClient
{
    public MySftpClient(string host, int port, string username, string password) : base(new PasswordConnectionInfo(host, port, username, password)) { }

    public new void Connect()
    {
        base.Connect();
    }
}

单元测试

[TestMethod]
public void Connect_Successful_Valid()
{
    var mySftpClient = new MySftpClient("localhost", 22, "root", "password");

    mySftpClient.Connect();
    // This errors because it actually tries to connect to a server using the above mock connection data
    // I cannot assert method Connect() was called once.
}
  1. 我可以模拟基类方法吗?或者我应该围绕 SftpClient 创建一个接口并将其注入 MySftpClient 的构造函数中,更喜欢组合而不是继承?

  2. 我应该对 SftpClient 使用 .Net DI 注入吗?services.AddScoped<ISftpClient, SftpClient>();

可能的解决方案

public class MySftpClient: IMySftpClient
{
    private ISftpClient sftpClient;

    public MySftpClient(
        ISftpClient sftpClient,
        string host,
        int port,
        string username,
        string password
    ) { // Instantiate PasswordConnectionInfo... }

    public void Connect()
    {
        sftpClient.Connect();
    }
}
C# 单元测试 继承 SFTP 包装器

评论

0赞 MakePeaceGreatAgain 9/28/2023
1. “或者我应该围绕 SftpClient 创建一个接口并将其注入到 MySftpClient 的构造函数中,更喜欢组合而不是继承?”是的。2. “我应该对 SftpClient 使用 .Net DI 注入吗?服务业。AddScoped<ISftpClient, SftpClient>();”您正在使用哪个(或如果有的话)DI 容器由您决定。
0赞 Mihai Socaciu 9/28/2023
似乎我无法传递到接口ISftpClient。该接口没有 Connect 方法来帮助我检查连接或传递凭据。如果您知道任何建议。接口 ISftpClient 来自 Renci.SshNet,它不是我的。我无法让 SftpClient 实现我自己的一些接口。PasswordConnectionInfo
0赞 Mihai Socaciu 9/28/2023
github.com/sshnet/SSH.NET/issues/193我发现了这个完全相同的问题。

答:

0赞 Mihai Socaciu 9/29/2023 #1

目前最好的解决方案是将我们自己的包装器排除在单元测试覆盖率之外。
https://github.com/sshnet/SSH.NET/issues/890#issuecomment-957179713
SftpClient

拉取请求与具有 Connect() 方法的接口合并。但目前它没有合并到 master 中。
https://github.com/sshnet/SSH.NET/pull/975

SftpClientWrapper