Moq:如何使用Mock.Of<>调用对象上的方法

时间:2016-12-07 19:48:28

标签: c# unit-testing mocking moq

在以下声明中,我希望将Navigation对象的IsNew标记设置为false,然后将false返回到IsCurrentStepUnlocked在该对象上调用的方法IsNew

然而,在第4行,当我检索1. var mockStatementInformation = Mock.Of<IStatementInformation>(); 2. mockStatementInformation.Navigation = new Navigation { IsNew = false }; 3. Mock.Get(mockStatementInformation).Setup(x => x.Navigation.IsCurrentStepUnlocked()).Returns(false); 4. var isNew = mockStatementInformation.Navigation.IsNew; 的值时,它是&#39;是&#39;

我似乎无法同时获取两者,在对象上设置值并设置某些内容以返回预定值。

public class Navigation
{        
    public Navigation()
    {
       IsNew = true;
    }

    public bool IsNew { get; set; }
}

导航,定义简单如下所示。

    <div id="foo">
        <div id="bar"></div>
        <div id="text">
            Some text.
        </div>
    </div>



    #foo {
      background: green;
      width: 100px;
      height: 20px;
      z-index: 1;
      position: relative;
      overflow: hidden;

    }

    #bar {
      background: red;
      width: 100%;
      position: absolute;
      left: 0;
      height: 100%;
      z-index: 2;
      transition: left 0.5s ease-in-out;
    }

    #text {
      z-index: 3;
      position: absolute;
      height: 100%;
      width: 100%;
    }


    /* REMOVE BELOW AND EDIT #bar LEFT: VALUE FOR STATIC LOADING BAR */

    #foo:hover #bar{
      left: 100%;
    }

如何使用Moq设置嵌套属性或调用方法?

1 个答案:

答案 0 :(得分:1)

参考:Moq Quickstart - linq-to-mocks

假设这个例子

public interface IStatementInformation {

    Navigation Navigation { get; set; }
}

public class Navigation {

    public Navigation() {
        IsNew = true;
    }

    public virtual bool IsNew { get; set; }

    public virtual bool IsCurrentStepUnlocked() {
        return true;
    }
}

默认情况下,方法和属性都返回true。

如此测试结果如预期那样

var mockStatementInformation = Mock.Of<IStatementInformation>(m =>
    m.Navigation == new Navigation { IsNew = false } &&
    m.Navigation.IsCurrentStepUnlocked() == false
);

Assert.IsFalse(mockStatementInformation.Navigation.IsCurrentStepUnlocked());
Assert.IsFalse(mockStatementInformation.Navigation.IsNew);