C# : Use IQueryable<T> as part of Unit Test

kenakamu

Kenichiro Nakamura

Posted on December 4, 2021

C# : Use IQueryable<T> as part of Unit Test

I sometimes need to write unit tests which uses IQueryable. For example, a repository or a service returns IQueryable, which I need to use inside unit test.

Scenario

Let's say I have an interface which returns IQueryable.

public interface IMyService
{
    public IQueryable<string> GetPeopleQuery();
}
Enter fullscreen mode Exit fullscreen mode

And then I need to test the following class.

public class SomeClass
{
    private IMyService myService;
    public SomeClass(IMyService myService)
    {
        this.myService = myService;
    }

    public List<string> HelloToPeople()
    {
        var people = myService.GetPeopleQuery().ToList();
        var helloPeople = people.Select(x=>x.Insert(0, "hello ")).ToList();
        return helloPeople;
    }
}
Enter fullscreen mode Exit fullscreen mode

Write Test

I use xUnit as an exmaple. I create IQueryable from the expected result and use it as Mock.Setup.

[Fact]
public void TestHello()
{
    var dummyQuery = (new List<string>() { "ken", "nozomi" }).AsQueryable();
    var mockedIMyService = new Mock<IMyService>();
    mockedIMyService.Setup(x => x.GetPeopleQuery()).Returns(dummyQuery);

    var someClass = new SomeClass(mockedIMyService.Object);
    var results = someClass.HelloToPeople();

    Assert.Equal("hello ken", results.First());
    Assert.Equal("hello nozomi", results.Last());
}
Enter fullscreen mode Exit fullscreen mode

That's it.

💖 💪 🙅 🚩
kenakamu
Kenichiro Nakamura

Posted on December 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related