C# : Use IQueryable<T> as part of Unit Test
Kenichiro Nakamura
Posted on December 4, 2021
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();
}
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;
}
}
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());
}
That's it.
💖 💪 🙅 🚩
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.