1

I have use Cosmosdb Container its abstract class. I need xUnit test case with mock using Moq library

public class SmsTemplateRepository : ISmsTemplateRepository
{
    private Container _container;

    public SmsTemplateRepository(CosmosClient dbClient, string databaseName, string containerName) 
    {
        _container = dbClient.GetContainer(databaseName, containerName);
    }

    public IEnumerable<SmsTemplate> GetAll()
    {
        return _container.GetItemLinqQueryable<SmsTemplate>(true);
    }

    **public async Task InsertAsync(SmsTemplate smsTemplate)
    {
        await _container.CreateItemAsync(smsTemplate);
    }**
}
Badro Niaimi
  • 959
  • 1
  • 14
  • 28
  • Could you share what attempt have you done to mock the object and which is the failure or error you are getting? – Matias Quaranta Nov 27 '19 at 16:11
  • No error i am not able to mock this method. public IEnumerable GetAll() { return _container.GetItemLinqQueryable(true); } –  Nov 28 '19 at 04:37
  • @DavinderSingh hi Davinder, were you able to solve this, do you have a working sample ? or can you mark an answer which worked for you ? – sumit sharma Jun 12 '20 at 07:15

1 Answers1

4

You have to mock the whole chain from the dependency you pass into the constructor of the repository.

  1. Create a list of templates you want to simulate GetAll to return:
var smsTemplates = new[]
{
  new SmsTemplate { Name = "Name1" },
  new SmsTemplate { Name = "Name3" }
}.AsQueryable()
 .OrderBy(x => x.Name);
  1. Create a mocked CosmosClient and a mocked Container and setup the CosmosClient mock to return the mocked container:
var container = new Mock<Container>();
var client = new Mock<CosmosClient>();

client.Setup(x => x.GetContainer(It.IsAny<string>(), It.IsAny<string>())
      .Returns(container.Object);
  1. Setup the mocked container to return the template list and pass in the mocked CosmosClient to the constructor of the repository:
container.Setup(x => x.GetItemLinqQueryable<SmsTemplate>(It.IsAny<bool>())
         .Returns(smsTemplates);
var repository = new SmsTemplateRepository(client.Object, ....);
  1. GetAll will now return the smsTemplates
jaspenlind
  • 349
  • 2
  • 6
  • it gives me error (Can not convert List to FeedResponse) while putting List in Returns, do you know an alternative ? – sumit sharma Jun 12 '20 at 08:02