Moq Example using out and ref needed

旧街凉风 提交于 2020-01-10 04:52:04

问题


I am trying to build a test against some legacy method that implement out parameters. Could you give me an example how to do this?


回答1:


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);
}



回答2:


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.




回答3:


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));


来源:https://stackoverflow.com/questions/3043612/moq-example-using-out-and-ref-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!