IQueryable Unit or Integration Test

I have a web api and I am showing the endpoint as follows:

api / holiday? name = {name}

This is the method to get the controller for 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 equal? I can verify that the result is not empty, but a bit confusing, how can I verify that 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); } 
+4
c # unit-testing linq asp.net-web-api testing
source share
3 answers

The test will look so that you can use linq to verify that the entire result matches your criteria.

 [TestMethod] public void GetHoliday_GetHolidayByName() { // Arrange string name = "Spain"; HolidaysController controller = new HolidaysController(); // Act IQueryable<Holiday> actionResult = controller.GetHolidayByName(name); //Assert Assert.IsNotNull(actionResult); Assert.IsTrue(actionResult.All(n => string.Equals(n.Name, name)); } 

Db is supposed to provide you with the required test data. Otherwise, you will need to make some design changes to allow for bullying / fake data.

If you connect to a real database, this is more of an integration test than a unit test.

+3
source share
 public interface IDbRepository { IQueryable<Holiday> GetHolidayByName(string name) } public class DbRepository : IDbRepository { public IQueryable<Holiday> GetHolidayByName(string name) { return db.Holiday.Where(n => string.Equals(n.Name, name)); } } private IDbRepository _dbRepository;//initialize, preferably through construtor public IQueryable<Holiday> GetHolidayByName(string name) { return _dbRepository.GetHolidayByName(name) } 
0
source share

First of all, I think you should test the results of db, but objects. Modify your method to give you the "Holiday" elements, then override the "equals" method on the object or simply compare the properties needed to validate

0
source share

All Articles