I have a wrapper around Renci.SshNet.Sftp.SftpClient
. I want to unit test this wrapper.
my wrapper
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();
}
}
unit test
[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.
}
Can I mock the base class method? Or should I make an interface around the SftpClient and inject it into the constructor of MySftpClient, prefering composition over inheritance?
Should I use .Net DI Injection for SftpClient?
services.AddScoped<ISftpClient, SftpClient>();
possible solution
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();
}
}
The best solution at the moment is to exclude our own SftpClient
wrapper from unit test coverage.
https://github.com/sshnet/SSH.NET/issues/890#issuecomment-957179713
A pull request was merged with an interface having Connect() method. But currently it is not merged into master.
https://github.com/sshnet/SSH.NET/pull/975