How to test a factory provided class is used

159 views Asked by At

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?

1

There are 1 answers

0
M Kenyon II On

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