模拟OData服务端点

时间:2018-06-12 15:05:39

标签: unit-testing odata moq

我正在尝试使用Moq来模拟OData服务上下文,以返回一个虚拟实体列表,以便我可以对其进行单元测试。我无法公开我的真实模型和应用程序,因此我创建了这个模拟应用程序,并且我公开的部分类似。

MyOdataApplication消耗我正在测试的ODataEndpoint。

public class MyApplication
{
   private readonly IODataContext _odataContext;

   public MyApplication(IODataContext odataContext){
       _odataContext = odataContext;
   }

   public async Task<IEnumerable<Book>> GetBooks(string authorName)
   {
      IEnumerable<Book> books = null;
      var query = (DataServiceQuery<Book>)_odataContext.Books.Where(x => x.Author = authorName);
      books = await query.ExecuteAsync().ToList();
      return books;
   }

   public bool async ValidateBooks(string authorName){
       var books = await GetBooks(authorname);
       //other code....
   }
}

我的Odata服务合约界面

public interface IODataContext
{
   global::Microsoft.OData.Client.DataServiceQuery<global::models.Book> Books { get; }
}

我的单元测试课程如下。

[TestFixture]
public class MyTestClass
{
   [Test]
   public void TestOdataFunctionality()
   {

     var mockODataEndpoint = new Mock<IODataContext>();

     //It fails here as its not able to convery IQueryable<Book> to DataServiceQuery<Book>
     mockODataEndpoint.Setup(x => x.GetBooks(It.IsAny<string>)).Returns(GetDummyBooks());

    var myApp = new MyApplication(mockODataEndpoint.Object);

    //This is my main method which I need to test.
    Task<bool> task = myApp.ValidateBooks("author name");
    var isvalid = task.Result;
    Assert.AreEqual(true, isvalid);
   }

   private DataServiceQuery<Book>GetDummyBooks()
   {
     var books = new List<Book>
        {
            new Book()
            {
                Name = "Book1",
                Author = "author name",
                //other properties...
            }
        };

        //Not sure how to achieve this. The below line is giving error ???
        return (DataServiceQuery<Book>)books.AsQueryable(); 
   }
} 

如何模拟Odata服务端点以便我可以测试我的ValidateBooks方法?

0 个答案:

没有答案