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.

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay