可查询单元或集成测试 [英] IQueryable Unit or Integration Test

查看:88
本文介绍了可查询单元或集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API,并且正在公开一个端点,如下所示:

I have a web api and I am exposing a endpoint like so:

api/Holiday?name = {name}

api/Holiday?name={name}

这是Web api的控制器get方法:

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

推荐答案

测试看起来像这样,您可以使用linq来验证返回的所有结果都满足您的条件.

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.

这篇关于可查询单元或集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆