I have a situation where I want to use a mocked object (using Moq) so I can create setup and expectations, but also want to supply some of the property values using the SpecFlow Table. Is there a convenient way to create a mock and supply the table for the seed 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?
}
There is an overload of CreateInstance
which takes a Func<T> methodToCreateTheInstance
. You can use it to pass an already setup mock as the base for the speclow 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");
}
If the object wasn't mocked you would simply use the assist helpers (See https://github.com/techtalk/SpecFlow/wiki/SpecFlow-Assist-Helpers ) but since you need the call to Setup(...) then it won't work.
However you can also use StepArgumentTransformation like 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)
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.