我正在为mocking
创建QueueClient
。我在GetQueueClient
中有ServiceBus class
。我正在使用以下代码。
using NUnit.Framework;
using Moq;
[TestFixture]
public sealed class FetchingTest
{
private Mock<IServiceBus> mockIServiceBus;
private Mock<QueueClient> queueClient1;
[TestFixtureSetUp]
public void Setup()
{
this.mockIServiceBus = new Mock<IServiceBus>();
this.queueClient1 = new Mock<QueueClient>();
}
[Test]
public void TestPagingUsesCorrectOffsets()
{
this.mockIServiceBus.Setup(p => p.GetQueueClient(Constants.FetcherQueueName)).Returns(queueClient1.Object); // Getting error here
}
}
服务总线类别:
using Microsoft.ServiceBus;
public class ServiceBus : IServiceBus
{
private static readonly string ServiceBusConnectionString =
ConfigurationManager.AppSettings[ConnectionStringNames.ServiceBus];
public QueueClient GetQueueClient(string queueName)
{
return QueueClient.CreateFromConnectionString(ServiceBusConnectionString, queueName);
}
}
它抛出错误
父级没有默认的构造函数。默认构造函数 必须明确定义。 System.NotSupportedException
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
请确保您依赖于抽象而非实现,以避免对实现存在问题。
public interface IServiceBus {
IQueueClient GetQueueClient(string queueName);
}
public class ServiceBus : IServiceBus {
private static readonly string ServiceBusConnectionString =
ConfigurationManager.AppSettings[ConnectionStringNames.ServiceBus];
public IQueueClient GetQueueClient(string queueName) {
return QueueClient.CreateFromConnectionString(ServiceBusConnectionString, queueName);
}
}
这种方式可以在测试时根据需要模拟抽象
[TestFixture]
public sealed class FetchingTest
{
private Mock<IServiceBus> mockIServiceBus;
private Mock<IQueueClient> queueClient1;
[TestFixtureSetUp]
public void Setup() {
this.mockIServiceBus = new Mock<IServiceBus>();
this.queueClient1 = new Mock<IQueueClient>();
}
[Test]
public void TestPagingUsesCorrectOffsets() {
//Arrange
this.mockIServiceBus
.Setup(_ => _.GetQueueClient(Constants.FetcherQueueName))
.Returns(queueClient1.Object);
//...
}
}