如何在服务结构中单元测试无状态服务

时间:2017-10-05 12:22:55

标签: unit-testing azure-service-fabric service-fabric-stateless

我想创建一个A类实例,它在我的单元测试中继承了StatelessService类。但我不能。我已经尝试了一切:嘲笑依赖,实现我自己的上下文等等。

当我尝试创建实例时,StatelessService会在内部的某处抛出NullReferenceException。

可以完成吗?

class A : StatelessService
{
    public A(StatelessServiceContext context) : base(context /* Here will be thrown NullReferenceException */)
    {
        // It will never even get there.
    }
}

class UnitTest
{
    public void TestMethod()
    {
        var activationContext = MOCK<ICodePackageActivationContext>();
        var context = new StatelessServiceContext(..., activationContext, ...);
        var a = new A(context); // Here will be thrown an exception.
    }
}

1 个答案:

答案 0 :(得分:2)

可以做到。但是,不要重新发明轮子,而是看看服务面料模拟https://github.com/loekd/ServiceFabric.Mocks

它包含完全适用于您的场景类型的有用助手。