Using Moq to Return a Mock Object from a Factory


/ Published in: C#
Save to your folder(s)

Note that the interface member is mockVar.Object mockVar won't cast to your interface.


Copy this code and paste it in your HTML
  1. public Sandbox GetMockedSandbox(string helloPrefix, string ackWord, int factor)
  2. {
  3. Sandbox retVal = new Sandbox();
  4.  
  5. var mockFactory = new Mock<IWorkerFactory>();
  6. var mockWorker = new Mock<IWorker>();
  7.  
  8. mockFactory.Expect(fac => fac.GetWorker(It.IsAny<int>())).Returns(mockWorker.Object);
  9.  
  10. mockWorker.Expect(ds => ds.Hello(It.IsAny<string>())).Returns((string s) => helloPrefix + s);
  11. mockWorker.Expect(ds => ds.Ping()).Returns(ackWord);
  12. mockWorker.Expect(ds => ds.MultiplyYourNumber(It.IsAny<int>())).Returns((int i) => i * factor);
  13.  
  14. retVal.ImplementationFactory = mockFactory.Object;
  15. return retVal;
  16. }

URL: http://code.google.com/p/moq/wiki/QuickStart

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.