4

我有一种情况,我想使用一个模拟对象(使用 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?

}
4

2 回答 2

3

如果没有模拟对象,您只需使用辅助助手(请参阅https://github.com/techtalk/SpecFlow/wiki/SpecFlow-Assist-Helpers),但由于您需要调用 Setup(...) 然后它行不通。

但是,您也可以像这样使用 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)
    ....
于 2012-12-19T13:36:24.860 回答
3

有一个重载CreateInstance需要一个Func<T> methodToCreateTheInstance. 您可以使用它来传递已设置的模拟作为 speclowCreateInstance方法的基础:

[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");
}
于 2012-12-19T13:29:23.803 回答