Reputation: 6090
I'm writing a Web API controller and right now I have the following code:
public class PicklistsController : ApiController
{
private readonly IPicklistRepository _repository;
public PicklistsController(IPicklistRepository repository)
{
_repository = repository;
}
public HttpResponseMessage GetPicklistValues(string entityName, string fieldName)
{
if(_repository.Exists(entityName, fieldName))
return Request.CreateResponse(HttpStatusCode.Accepted, _repository.Get(entityName, fieldName));
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
I'm trying to test this method and all I really want to do is verify that the HttpResponseMessage contains values in the POCO PicklistItem when the repository finds this combination of values. Being new to this framework, I don't understand the internal workings of HttpResponseMessage very well, and what I've found on this site and through general googling tells me to use various ReadAsync methods on its Content, but I don't really want to do use async if I can avoid it. I really just want to verify that the thing I stuffed into the object I'm returning is in the object when I return it. Here's what I have so far with the unit test (using JustMock to setup the repository, Target is the CUT):
public void Returns_Picklist_Item_JSON_When_Results_Exist()
{
Repository.Arrange(repo => repo.Exists(EntityName, FieldName)).Returns(true);
const int value = 2;
const string label = "asdf";
var mynewPicklistItem = new PicklistItem() { Label = label, Value = value };
Repository.Arrange(repo => repo.Get(EntityName, FieldName)).Returns(Enumerable.Repeat<PicklistItem>(mynewPicklistItem, 1));
var response = Target.GetPicklistValues(EntityName, FieldName);
//Assert.IsTrue(I don't know what to do here -- suggestions appreciated);
}
Any ideas for the Assert? Or am I barking up the wrong tree/fundamentally misunderstanding how this should be working? Thanks...
Upvotes: 20
Views: 24060
Reputation: 4063
If the Content
is an object then try casting it as ObjectContent
- the Value
property should contain your object.
If it's a StreamContent
though then I don't know of other way than to do ReadAsAsync
. Still you can block on the Result of the task to see the response.
Here is an example:
var response = Target.GetPicklistValues(EntityName, FieldName);
ObjectContent objContent = response.Content as ObjectContent;
PicklistItem picklistItem = objContent.Value as PicklistItem;
Upvotes: 19
Reputation: 24500
I am using Web API 2.1 and there is a function called TryGetContentValue
:
[Test]
public void TheTestMethod()
{
// arrange
var ctrl = new MyController();
ctrl.Request = Substitute.For<HttpRequestMessage>(); // using nSubstitute
ctrl.Configuration = Substitute.For<HttpConfiguration>();
// act
HttpResponseMessage result = ctrl.Get();
MyResponse typedresult;
result.TryGetContentValue(out typedresult); // <= this one
// assert
}
Upvotes: 19