Вопрос по c# – Назначение параметров / ref в Moq

233

Можно ли назначитьout/ref параметр с помощью Moq (3.0+)?

Я смотрел на использованиеCallback(), ноAction<> не поддерживает параметры ref, потому что он основан на обобщениях. Я также хотел бы поставить ограничение (It.Is) на входеref параметр, хотя я могу сделать это в обратном вызове.

Я знаю, что Rhino Mocks поддерживает эту функцию, но проект, над которым я работаю, уже использует Moq.

Error: User Rate Limit ExceededIt.IsAny<T>()Error: User Rate Limit Exceededref It.Ref<T>.IsAnyError: User Rate Limit Exceeded.Callback()Error: User Rate Limit Exceeded.Returns()Error: User Rate Limit Exceededmy answer below. stakx

Ваш Ответ

9   ответов
1

60

public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}

It.Ref<T>.IsAnyin

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Richard Szalay
1

[Test]
public void TestForOutParameterInMoq()
{
  //Arrange
  _mockParameterManager= new Mock<IParameterManager>();

  Mock<IParameter > mockParameter= new Mock<IParameter >();
  //Parameter affectation should be useless but is not. It's really used by Moq 
  IParameter parameter= mockParameter.Object;

  //Mock method used in UpperParameterManager
  _mockParameterManager.Setup(x => x.OutMethod(out parameter));

  //Act with the real instance
  _UpperParameterManager.UpperOutMethod(out parameter);

  //Assert that method used on the out parameter of inner out method are really called
  mockParameter.Verify(x => x.FunctionCalledInOutMethodAfterInnerOutMethod(),Times.Once());

}
Error: User Rate Limit Exceeded Richard Szalay
275

public interface IService
{
    void DoSomething(out string a);
}

[TestMethod]
public void Test()
{
    var service = new Mock<IService>();
    var expectedValue = "value";
    service.Setup(s => s.DoSomething(out expectedValue));

    string actualValue;
    service.Object.DoSomething(out actualValue);
    Assert.AreEqual(expectedValue, actualValue);
}

ref

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededassigningError: User Rate Limit ExceededSetup Richard Szalay
Error: User Rate Limit Exceededcode.google.com/p/moq/wiki/QuickStart
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
73

EDITError: User Rate Limit Exceeded

  .Setup(x=>x.Method(out d))
  .Callback(myDelegate)
  .Returns(...); 

Error: User Rate Limit Exceeded

...
.Callback(new MyDelegate((out decimal v)=>v=12m))
...

For Moq version before 4.10:

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

public static class MoqExtensions
{
    public delegate void OutAction<TOut>(out TOut outVal);
    public delegate void OutAction<in T1,TOut>(T1 arg1, out TOut outVal);

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, TOut>(this ICallback<TMock, TReturn> , OutAction<TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(, action);
    }

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, T1, TOut>(this ICallback<TMock, TReturn> , OutAction<T1, TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(, action);
    }

    private static IReturnsThrows<TMock, TReturn> OutCallbackInternal<TMock, TReturn>(ICallback<TMock, TReturn> , object action)
        where TMock : class
    {
        .GetType()
            .Assembly.GetType("Moq.MethodCall")
            .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, ,
                new[] { action });
        return  as IReturnsThrows<TMock, TReturn>;
    }
}

Error: User Rate Limit Exceeded

public interface IParser
{
    bool TryParse(string token, out int value);
}

Error: User Rate Limit Exceeded

    [TestMethod]
    public void ParserTest()
    {
        Mock<IParser> parserMock = new Mock<IParser>();

        int outVal;
        parserMock
            .Setup(p => p.TryParse("6", out outVal))
            .OutCallback((string t, out int v) => v = 6)
            .Returns(true);

        int actualValue;
        bool ret = parserMock.Object.TryParse("6", out actualValue);

        Assert.IsTrue(ret);
        Assert.AreEqual(6, actualValue);
    }



EditError: User Rate Limit Exceeded

public static ICallbackResult OutCallback<TOut>(this ICallback , OutAction<TOut> action)
{
    return OutCallbackInternal(, action);
}

public static ICallbackResult OutCallback<T1, TOut>(this ICallback , OutAction<T1, TOut> action)
{
    return OutCallbackInternal(, action);
}

private static ICallbackResult OutCallbackInternal(ICallback , object action)
{
    .GetType().Assembly.GetType("Moq.MethodCall")
        .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, , new[] { action });
    return (ICallbackResult);
}

Error: User Rate Limit Exceeded

public interface IValidationRule
{
    void Validate(string input, out string message);
}

[TestMethod]
public void ValidatorTest()
{
    Mock<IValidationRule> validatorMock = new Mock<IValidationRule>();

    string outMessage;
    validatorMock
        .Setup(v => v.Validate("input", out outMessage))
        .OutCallback((string i, out string m) => m  = "success");

    string actualMessage;
    validatorMock.Object.Validate("input", out actualMessage);

    Assert.AreEqual("success", actualMessage);
}
Error: User Rate Limit Exceededgithub.com/moq/moq4/commit/…Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededhere.
0

string firstOutParam = "first out parameter string";
string secondOutParam = 100;
mock.SetupAllProperties();
mock.Setup(m=>m.Method(out firstOutParam, out secondOutParam)).Returns(value);

mock.SetupAllProperties();return valueYourMethod

46

:

// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
Error: User Rate Limit Exceeded Richard Szalay
Error: User Rate Limit Exceeded
2

public static class MoqExtensions
{
    public static IReturnsResult<TMock> DelegateReturns<TMock, TReturn, T>(this IReturnsThrows<TMock, TReturn> mock, T func) where T : class
        where TMock : class
    {
        mock.GetType().Assembly.GetType("Moq.MethodCallReturn`2").MakeGenericType(typeof(TMock), typeof(TReturn))
            .InvokeMember("SetReturnDelegate", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
                new[] { func });
        return (IReturnsResult<TMock>)mock;
    }
}

public delegate int MyMethodDelegate(int x, ref int y);

    [TestMethod]
    public void TestSomething()
    {
        //Arrange
        var mock = new Mock<ISomeInterface>();
        var y = 0;
        mock.Setup(m => m.MyMethod(It.IsAny<int>(), ref y))
        .DelegateReturns((MyMethodDelegate)((int x, ref int y)=>
         {
            y = 1;
            return 2;
         }));
    }
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
18

Error: User Rate Limit Exceeded Richard Szalay

Похожие вопросы