组合SpecFlow表和Moq模拟对象

时间:2012-12-19 12:39:50

标签: c# moq specflow

我有一种情况,我想使用模拟对象(使用Moq),因此我可以创建设置和期望,但也想使用SpecFlow表提供一些属性值。有没有一种方便的方法来创建模拟并为种子值提供表?

// Specflow feature

Scenario Outline: MyOutline
Given I have a MyObject object as
| Field | Value     |
| Title | The Title |
| Id    | The Id    |


// Specflow step code    

Mock<MyObject> _myMock;

[Given(@"I have a MyObject object as")]
public void GivenIHaveAMyObjectObjectAs(Table table)
{
   var obj = table.CreateInstance<MyObject>();

   _myMock = new Mock<MyObject>();

   // How do I easily combine the two?

}

2 个答案:

答案 0 :(得分:3)

CreateInstance超载需要Func<T> methodToCreateTheInstance。您可以使用它来传递已设置的模拟作为speclow CreateInstance方法的基础:

[Given(@"I have a MyObject object as")]
public void GivenIHaveAMyObjectObjectAs(Table table)
{
   _myMock = new Mock<MyObject>();
   //you need to do all the setup before passing _myMock to table.CreateInstance
   _myMock.Setup(o => o.SomeProperty).Returns("someValue"); 

   var obj = table.CreateInstance<MyObject>(() => _myMock.Object);

   _myMock.VerifySet(foo => foo.Title = "The Title");
}

答案 1 :(得分:3)

如果对象未被嘲笑,您只需使用辅助助手(请参阅https://github.com/techtalk/SpecFlow/wiki/SpecFlow-Assist-Helpers),但由于您需要调用安装程序(...),因此无法使用。

但是你也可以像这样使用StepArgumentTransformation

    [StepArgumentTransformation]
    public Mock<MyData> MockMyDataTransform(Table table)
    {
        MyData myData = new Mock<MyData>();
        var row = table.Rows[0];
        if (table.ContainsColumn("MyField"))
        {
            myData.Setup(x=>x.MyField).Returns(row["MyField"]);
        }
     ....
    }

并将其与

一起使用
    [Given(@"something like:")]
    private void GivenSomethingLike(Mock<MyData> myData)
    ....