我有一个类别<代码>Iot Hubservice,该类别取决于C# IoT Hub SDK sIot HubserviceClient
(SDK的五2版,目前正在审查之中),以对IoT/2007/5进行各种查询。 我试图通过撰写一些测试和模拟依赖物来提高我这一类人的可靠性:
[Fact]
public async Task GetDeviceByIdAsync_ValidDeviceId_ReturnsDevice()
{
// Arrange
string deviceId = "testDeviceId";
Device expectedDevice = new Device(deviceId);
// Create a mock IotHubServiceClient
Mock<IotHubServiceClient> mockIotHubServiceClient = new Mock<IotHubServiceClient>();
mockIotHubServiceClient
.Setup(c => c.Devices.GetAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(expectedDevice);
// Create an instance of IoTHubService using the mock client
IotHubService ioTHubService = new IotHubService(mockIotHubServiceClient.Object);
// Act
Device result = await ioTHubService.GetDeviceByIdAsync(deviceId);
// Assert
Assert.Equal(expectedDevice, result);
mockIotHubServiceClient.Verify(c => c.Devices.GetAsync(deviceId, default(CancellationToken)), Times.Once);
}
然而,我无法在模拟伊特赫特·赫特·埃赫特时作出判断,在进行我的测试时会遇到以下错误:
System.NotSupportedException: Invalid setup on a non-virtual (overable in VB) member: mock => mock. 装置'
我的理解是,“DevicesClient”的基本原理是密封的,但我很想知道,是否有办法解决这一问题?
Edit: What my IotHubService
class looks like:
public class IotHubService : IIotHubService
{
protected readonly IotHubServiceClient _iotHubServiceClient;
public IotHubService(string connectionString)
{
_iotHubServiceClient = new IotHubServiceClient(connectionString);
}
public IotHubService(IotHubServiceClient iotHubServiceClient)
{
_iotHubServiceClient = iotHubServiceClient;
}
public async Task<Device> GetDeviceByIdAsync(string deviceId)
{
if (string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
}
try
{
return await _iotHubServiceClient.Devices.GetAsync(deviceId);
}
catch (Exception)
{
throw;
}
}
}