I have a web api and I am exposing a endpoint like so:
api/Holiday?name={name}
This is the controller get method for the web api:
public IQueryable<Holiday> GetHolidayByName(string name)
{
return db.Holiday.Where(n => string.Equals(n.Name, name));
}
How can I write a unit/integration test for this that checks the names are equal? I can check the result is not null however bit confused how I can check the names are equal:
[TestMethod]
public void GetHoliday_GetHolidayByName()
{
// Arrange
HolidaysController controller = new HolidaysController();
// Act
IQueryable<Holiday> actionResult = controller.GetHolidayByName("Spain");
//Assert
Assert.IsNotNull(actionResult);
//any attempt to check names are equal results in a fail
//For instance this fails
var result = controller.GetHolidayByName("Spain") as OkNegotiatedContentResult<Holiday>;
Assert.AreEqual("Spain", result.Content.Name);
}
First of all, I think that you should be testing db results but objects. Mock your method to give you "Holiday" Items, then override the "equals" method on the object, or just comparte the properties you need to check
The test would look like this where you can use linq to verify that all the result returned satisfy your criteria.
The assumption here is that the db will provide you with the test data you want. Otherwise you will have to make some design changes to allow for providing mocked/fake data.
If you are connecting to an actual database then this is more an integration test rather than a unit test.