Join a SpecFlow table and a Moq mocked object

I have a situation where I want to use a mocked object (using Moq) so that I can create settings and expectations, but also want to provide some property values ​​using the SpecFlow table. Is there a convenient way to create a layout and provide a table for the initial values?

// 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
source share
2 answers

There is an overload of CreateInstance that accepts a Func<T> methodToCreateTheInstance . You can use it to pass an already configured layout as a base for the CreateInstance method:

 [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"); } 
+3
source

If the object wasn’t being mocked, you just used auxiliary helpers (see https://github.com/techtalk/SpecFlow/wiki/SpecFlow-Assist-Helpers ), but since you need a call to install (...), then it will not work.

However, you can also use a StepArgumentTransformation similar to this

  [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"]); } .... } 

and use it with

  [Given(@"something like:")] private void GivenSomethingLike(Mock<MyData> myData) .... 
+3
source

All Articles