2

I want to create an instance of class A which inherits class StatelessService in my unit test. But I can't. I've tried everything: mocking dependencies, implementing my own contexts and etc.

When I try to create an instance, StatelessService throws NullReferenceException somewhere inside.

Can it be done at all?

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.
    }
}
Ivan Zyranau
  • 879
  • 2
  • 14
  • 33
  • Provide some code as a [mcve] that better demonstrates your problem. It can be used to help identify the problem and derive any possible solutions. – Nkosi Oct 05 '17 at 12:55
  • @Nkosi I updated the question providing minimal pseudo-code. – Ivan Zyranau Oct 05 '17 at 14:26
  • You're also going to have to be more descriptive as to when and where you get the error. Take a look at the sample here and see if you can find an example that helps https://github.com/Azure-Samples/service-fabric-watchdog-service/blob/90c6418a99b5fcd777a5b7c2a5f6443fdcc9f42a/TestStatelessService/TestStatelessService.cs – Nkosi Oct 05 '17 at 14:42
  • @Nkosi service fabric throws NullReferenceException internally if you are trying to create an instance of a stateless service. What's to describe? – Ivan Zyranau Oct 05 '17 at 14:48

1 Answers1

3

It can be done. But instead of re inventing the wheel, have a look at service fabric mocks https://github.com/loekd/ServiceFabric.Mocks

It contains useful helpers for exactly your type of scenario.

Esben Bach
  • 664
  • 4
  • 23
  • I've tried using it, it doesn't work and throws all kinds of exceptions on different versions of service fabric. Anyway, I've resolved my issue. It was with a type initializer and some static properties not being set in *my* class. This has nothing to do with service fabric. – Ivan Zyranau Oct 07 '17 at 20:05
  • 2
    @EwanCoder, please consider posting feedback /issues to the package, so everyone can benefit. https://github.com/loekd/ServiceFabric.Mocks/issues – LoekD Oct 09 '17 at 06:18