微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何使用Moq框架对天蓝色服务结构进行单元测试?

我计划使用Moq对我的Azure服务结构应用程序进行单元测试.我在这里看到了一些例子https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs.我看到的测试似乎实际上写的是可靠的字典而不是嘲笑.有没有办法模拟可靠字典中的添加/删除?我如何对下面的内容进行单元测试

public async Task<bool> AddItem(MyItem item)
{
    var items = await StateManager.GetorAddAsync<IReliableDictionary<int, MyItem>>("itemDict");

    using (ITransaction tx = this.StateManager.CreateTransaction())
    {
        await items.AddAsync(tx, item.Id, item);
        await tx.CommitAsync();
    }
    return true;
}

解决方法:

首先在服务中设置DI,以便注入模拟StateManager.您可以使用将IReliableStateManagerReplica作为参数的构造函数来执行此操作

public class MyStatefulService : StatefulService 
{
    public MyStatefulService(StatefulServiceContext serviceContext, IReliableStateManagerReplica reliableStateManagerReplica)
        : base(serviceContext, reliableStateManagerReplica)
    {
    }
}

然后在测试中,当您在创建被测系统(服务)时,使用模拟IReliableStateManagerReplica

var reliableStateManagerReplica = new Mock<IReliableStateManagerReplica>();

var codePackageActivationContext = new Mock<ICodePackageActivationContext>();
var serviceContext = new StatefulServiceContext(new NodeContext("", new NodeId(8, 8), 8, "", ""), codePackageActivationContext.Object, string.Empty, new Uri("http://boo.net"), null, Guid.NewGuid(), 0L);

var myService = new MyService(serviceContext, reliableStateManagerReplica.Object);

然后设置reliableStateManagerReplica以返回模拟可靠字典.

var dictionary = new Mock<IReliableDictionary<int, MyItem>>();
reliableStateManagerReplica.Setup(m => m.GetorAddAsync<IReliableDictionary<int, MyItem>>(name).Returns(Task.Fromresult(dictionary.Object)); 

最后,在模拟字典中设置任何模拟行为.

编辑:更新了示例代码以正确使用Moq.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐