问题
I am using pactNet to test an API which should return an array of a flexible length.
If i call "myApi/items/" it should return a list of items where the consumer does not know the exact size of. So the answer should look like this:
[
{
"id": "1",
"description": "foo"
},
{
"id": "2",
"description": "foo2"
},
{
"id": "3",
"description": "foo3"
}
]
or this:
[
{
"id": "4",
"description": "foo4"
},
{
"id": "2",
"description": "foo2"
}
]
How do I create the contract for this interaction?
In the documentation is an example in Ruby, but I cannot find the equivalent in C#.
I am using pactNet version 2.1.1.
Edit: Here is an example how it should look like. What I want to know is how do I declare that the body should contain an array of items with a flexible length.
[Test]
public void GetAllItems()
{
//Arrange
_mockProviderService
.Given("There are items")
.UponReceiving("A GET request to retrieve the items")
.With(new ProviderServiceRequest
{
Method = HttpVerb.Get,
Path = "/items/",
Headers = new Dictionary<string, object>
{
{ "Accept", "application/json" }
}
})
.WillRespondWith(new ProviderServiceResponse
{
Status = 200,
Headers = new Dictionary<string, object>
{
{ "Content-Type", "application/json; charset=utf-8" }
},
Body = // array of items with some attributes
// (somthing like: {"id": "2", "description": "foo"})
// with flexible length
});
var consumer = new ItemApiClient(_mockProviderServiceBaseUri);
//Act
var result = consumer.GetItems();
//Assert
Assert.AreEqual(true, result.Count > 0);
_mockProviderService.VerifyInteractions();
data.Dispose();
}
回答1:
Sounds like you are looking for the MinTypeMatcher.
The body part would look something like below:
Body = Match.MinType(new { id: "1", description: "foo" }, 1)
回答2:
So, what if I want to Match the type of an object that has a property that is a list or array?
if you do a Match.Type(new myType()) and the number of elements in the array or list property is not exactly the same, the test will fail. You will see an error like this:
Description of differences
--------------------------------------
* Actual array is too long and should not contain a Hash at $.data.itinerary[2]
回答3:
For a nested array scenario like @SlimSjakie asked, just repeat Match.MinType at the property that has array. For example, the following Person object has Address property as an array.
Person = Match.MinType(new
{
FirstName = Match.Type("string"),
LastName = Match.Type("string"),
Address = Match.MinType(new
{
Street = Match.Type("string"),
Town = Match.Type("string"),
State = Match.Type("string"),
Postcode = Match.Type("string"),
Country = Match.Type("string")
}, 1)
}, 1)
来源:https://stackoverflow.com/questions/47346369/pact-net-consumer-test-flexible-length-array