单元测试代码使用IQueryable [英] Unit testing code using IQueryable

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

问题描述

我被要求为某些功能编写一些单元测试,但坦率地说,我不太了解这种代码的需要或实用性。

I'm asked to write some unit tests for some functionality, but quite frankly I'm not so sure about the need or usefulness of doing so for this particular piece of code. I'm in no way trying to question the need or usefulness of unit testing in general.

有关代码很简单,可以得到用了很多基本上它是围绕.Skip()和.Take()扩展方法的包装。在我看来,整个方法的合法性是有问题的。

The code in question is very trivial and gets used alot. Basically it's a wrapper around the .Skip() and .Take() extension methods. In my opinion the legitimacy of the methods as a whole is questionable.

代码基本是这样的:

public IQueryable<T> Page(IQueryable<T> query, int page, int size)
{
    if(query == null) throw new ArgumentNullException("query");
    if(page < 0) throw new ArgumentOutOfRangeException("page"); 
    if(page < 0) throw new ArgumentOutOfRangeException("size"); 

    return query.Skip(page * size).Take(size);
}

当然我可以单元测试预期的异常,但还有什么?可能很好,我错过了一点,那么这是什么呢?

Of course I can unit test for the expected exceptions, but what else? Could very well be that I'm missing the point, so what's up with this?

推荐答案

你可以测试很多东西这里:

You can test quite a few things here:


  1. 检查正确的保护(通过无效参数时抛出的异常)。

  2. 检查跳过是否使用正确的参数调用。

  3. 检查 Take 被调用了正确的参数。

  4. 检查跳过是否在之前调用

  1. Check for proper guards (the exceptions that are thrown when invalid parameters are passed).
  2. Check that Skip was called with the correct parameter.
  3. Check that Take was called with the correct parameter.
  4. Check that Skip was called before Take.

点数2 - 4是最好的测试与模拟。这个测试被称为基于交互的测试。

Points 2 - 4 are best tested with a mock. A mocking framework comes in handy here.
This kind of testing is called "interaction-based testing".

你也可以使用通过使用带有数据的列表调用被测试方法,并检查返回的数据是否是正确的子集。

You could also use "state-based testing" by calling the method under test with a list with data and check that the returned data is the correct subset.

对于点2的测试可能如下所示:

A test for point 2 could look like this:

public void PageSkipsThePagesBeforeTheRequestedPage()
{
    var sut = new YourClass();
    var queryable = Substitute.For<IQueryable<int>>();

    sut.Page(queryable, 10, 50);

    queryable.Received().Skip(500);
}

此测试使用 NSubstitute 作为嘲笑框架。

This test uses NSubstitute as mocking framework.

这篇关于单元测试代码使用IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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