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 AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay