Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Use the MoqAutoMocker that comes with StructureMap 2.5.3?

I'm trying to use the MoqAutoMocker class that comes with StructureMap and I can't find any examples of how it should be used. All I have to go on is the example at the StructureMap site that uses RhinoMocks.

What I'm trying to do is get reference to one of my auto-mocked/injected dependencies using the Get method. According to that link above, I should be able to do something like this

    // This retrieves the mock object for IMockedService
    autoMocker.Get<IMockedService>().AssertWasCalled(s => s.Go());

Note how you can use AssertWasCalled, which inidcates that the Get function returns a reference to the RhinoMocks Mock object? This same bit of code doesn't work for me when I use the MoqAutoMocker.

I have a class SignInController that depends upon an ISecurityService in the constructor. Using the MoqAutoMocker like the RhinoAutoMocker is used in the example, I think I should be able to do this...

var autoMocker = new MoqAutoMocker<SignInController>();
autoMocker.Get<ISecurityService>().Setup(ss => ss.ValidateLogin
(It.IsAny<string>(), It.IsAny<string>())).Returns(true); 

But the problem is that I never get access to the Setup method. In this case, the call to autoMocker.Get seems to be returning an instance of ISecurityService and not Mock<ISecurityService>

Has anyone successfully used MoqAutoMocker this way? Am I just doing it wrong?

like image 557
JamieGaines Avatar asked Jun 03 '09 14:06

JamieGaines


2 Answers

I recently ran into a simillar problem. It seems that the solution is to do something like this:

var autoMocker = new MoqAutoMocker<SignInController>();
var mock = autoMocker.Get<ISecurityService>();
Mock.Get(mock).Setup(ss => ss.ValidateLogin
(It.IsAny<string>(), It.IsAny<string>())).Returns(true);

I have also posted a lengthier example on my blog: Setting Expectations With StructureMap’s MoqAutoMocker.

like image 189
Joel Abrahamsson Avatar answered Sep 28 '22 00:09

Joel Abrahamsson


autoMocker.Get<ISecurityService>()
will return ISecurityService and you can't Setup on it. In contrary
Mock.Get(mock)
will return Moq.Mock, then you could Setup on it.

like image 44
Brian Vo Avatar answered Sep 28 '22 01:09

Brian Vo