IQueryable Unit or Integration Test

2019-06-26 01:20发布

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);        
}

3条回答
forever°为你锁心
2楼-- · 2019-06-26 01:29
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)
    }
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-26 01:30

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

查看更多
Deceive 欺骗
4楼-- · 2019-06-26 01:51

The test would look like this where you can use linq to verify that all the result returned satisfy 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));
}

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.

查看更多
登录 后发表回答