1

Using Moq is there a way to mock an object that exists in the call chain of the system under test?

So in my test:

var x = mock.Create<ISystemUnderTest>();
var result = x.DoSomething();

Then in my system under test:

public Person User => return new Person(){ Name="Smithy" };

public string DoSomething(){
   var x = User.Name; // I want to use a mock instance here of User
}

Can I mock User when it's not being provided as a parameter? But just a member of the call chain?

Alejandro
  • 7,290
  • 4
  • 34
  • 59
Tony D.
  • 551
  • 1
  • 10
  • 26
  • 3
    To even consider using a mock, you need to inject the dependency. But here you're `new`ing it yourself, so you can't replace it from outside. Besides, you seem to be mocking the system under test, not testing the real thing. – Alejandro Mar 10 '22 at 19:43
  • 1
    If the `User` property is defined inside the `ISystemUnderTest` then you can do something like this: `x.SetupGet(y => y.User).Returns(testUser);` BUT as it was said you should NOT mock your SUT only its dependencies. – Peter Csala Mar 11 '22 at 08:56

0 Answers0