0

I have a section of code that calls a factory, and then uses the returned object.

var myServiceObject = factoryService.GetTheObject(myParam);
myServiceObject.DoSomeWork(someData, moreData); // returns void

I'm writing a test with Automock where I want to verify that I call the factory and that I attempt to use the object.

For mocking the factory I'm assuming I need it to return an instance?

mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
   .Returns({insertSomething});

I was going to use a mock object, and do something like this:

mock.Mock<IMyService>().Setup(x => x.DoSomeWork(...));
var mockOfMyService = mock.Provide<IMyService>(new MockOfMyService()); // MockOfMyService inherits from IMyService
mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
   .Returns(mockOfMyService);
...
mock.Mock<IFactoryService>().Verify(...); // This passes
mock.Mock<IMyService>().Verify(x => x.DoSomeWork(...), Times.Once); // This errors

But I'm getting an invalid cast exception on the verify. Any good examples out there? What am I doing wrong?

M Kenyon II
  • 4,136
  • 4
  • 46
  • 94
  • Assuming you have the Factory wrapped in tests, as well as the object(s) it's returning, those suites should verify that you're getting the right object and that it works correctly. Then when you mock the factory in these tests, just return the concrete implementation of whatever the factory is supposed to return at that point (like you indicate), and then run it. Since the method returns void, I assume it's mutating something (the data you pass in?), so set an initial state on that data, run it through your instance, and at the end of the test assert the data has been mutated. – Nik P May 18 '20 at 20:55
  • In this case, we're sending data. And yes, I'm assuming the class itself is tested. I just want to ensure that this method is calling that. In this instance, there are a couple other things tested that I've left out for the sake of the example. – M Kenyon II May 19 '20 at 12:01

1 Answers1

0

So, for this one, I received some help outside of SO. Here's what worked for me:

mock.Mock<IMyService>().Setup(x => x.DoSomeWork(...));
var mockOfMyService = mock.Mock<IMyService>().Object; // Slight change here
mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
   .Returns(mockOfMyService);
...
mock.Mock<IFactoryService>().Verify(...); // This passes
mock.Mock<IMyService>().Verify(x => x.DoSomeWork(...), Times.Once); // And now this passes
M Kenyon II
  • 4,136
  • 4
  • 46
  • 94