DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

5 2

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs