1

If I have:

public class TestClass
{
  public void Method1(object data)
  {
    var otherClass = UnityContainer.Resolve(data) as OtherClass;
    var result = otherClass.Method2();
  }
}

And I want to run the actual implementation of OtherClass rather than mocking it using:

var testClass = new Mock<TestClass>() { CallBase = true }

(I'm writing dependency injection tests)

Is there a way that I can test the return value of OtherClass().Method2()?

Specifically, I want to do:

var testClass1 = new Mock<TestClass>() { CallBase = true }
var testClass2 = new Mock<TestClass>() { CallBase = true }

Assert.Same(resultOfTestClass1OtherClassMethod2, resultOfTestClass2OtherClassMethod2)

to check that I'm returning the same instance, and I've got things set up correctly in Unity.

Any helpers out there?

Adam
  • 129
  • 11
  • 2
    You should really only mock interfaces, but if you want to mock a concrete class then the method you wish to mock should needs to be marked virtual: https://stackoverflow.com/questions/20400734/c-sharp-how-do-i-mock-a-class-without-an-interface – LordWilmore Nov 24 '17 at 15:38
  • 1
    The question in its current state is unclear as it is incomplete. Read [ask] and then provide a [mcve] that can be used to better understand and reproduce your problem. If calling `new OtherClass()` withing method then no dependency injection is being done. – Nkosi Nov 24 '17 at 16:31
  • @Nkosi I've updated the example to bring it closer to my code. I can't see how I can inject OtherClass as it has a parameter in its constructor that will only be defined at run time. Is there a way? – Adam Nov 24 '17 at 17:45
  • @LordWilmore Thank you – Adam Nov 24 '17 at 17:46
  • @Adam well since you have not shown other class there is not much that can be said on other approaches. You are currently doing a service-locator anti-pattern and not DI. You need to review your design. – Nkosi Nov 24 '17 at 17:55

0 Answers0