开发者

Moq Example using out and ref needed

I am trying to build a test against some legacy method that implement out parameters. Could you give me an example how to d开发者_运维百科o this?


Just assign the out or ref parameter from the test.

Given this interface:

public interface ILegacy
{
    bool Foo(out string bar);
}

You can write a test like this:

[TestMethod]
public void Test13()
{
    string bar = "ploeh";

    var legacyStub = new Mock<ILegacy>();
    legacyStub.Setup(l => l.Foo(out bar))
        .Returns(true);

    Assert.IsTrue(legacyStub.Object.Foo(out bar));
    Assert.AreEqual("ploeh", bar);
}


Anything wrong with the second example at the top of https://github.com/moq/moq4/wiki/Quickstart ? You really should be giving examples of what you're trying to do if you're not going to look for things like this.


Incidentally if you want to use moq (currently) to mock the out parameter too you'll also have to do the following hoop jump. Lets say that you wanted to mock an out parameter that returned another mocked object e.g.

var mockServiceA = new Mock<IMyService>();
var mockServiceOutput = new Mock<IMyServiceOutput>();

// This will not work...
mockServiceA.Setup(svc => svc.DoSomething(out mockServiceOutput.Object));

// To have this work you have to do the following
IMyServiceOutput castOutput = mockServiceOutput.Object;
mockServiceA.Setup(svc => svc.DoSomething(out castOutput));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜