提问人:Mihai Socaciu 提问时间:9/28/2023 最后编辑:Mihai Socaciu 更新时间:9/29/2023 访问量:58
SftpClient 单元测试派生类和模拟基类 C#
SftpClient Unit test derived class and mock base class C#
问:
我有一个包装器.我想对这个包装器进行单元测试。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.
}
我可以模拟基类方法吗?或者我应该围绕 SftpClient 创建一个接口并将其注入 MySftpClient 的构造函数中,更喜欢组合而不是继承?
我应该对 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();
}
}
答:
0赞
Mihai Socaciu
9/29/2023
#1
目前最好的解决方案是将我们自己的包装器排除在单元测试覆盖率之外。
https://github.com/sshnet/SSH.NET/issues/890#issuecomment-957179713SftpClient
拉取请求与具有 Connect() 方法的接口合并。但目前它没有合并到 master 中。
https://github.com/sshnet/SSH.NET/pull/975
评论
PasswordConnectionInfo