vendredi 4 décembre 2015

How to unit test OData Client?

I'm using Web Api OData v4 on the server and OData Client code generator on the client. It works fine, but I don't know how to test the code on the client.

On the server I expose a "Levels" dbSet.

Here's a snippet code on the client:

public class LevelViewer
{
   public virtual DefaultContainer Container{get;set;} //t4 template generated

   public LevelViewer(DefaultContainer container=null)
   {
        if(container==null)
          {
            Container=new DefaultContainer(new Uri("http://blabla"));
          }
   }
}

//I want to test this (actually there are more things, this is an example)
public List<Level>GetRootLevels()
{
  return DefaultContainer.Levels.Where(l=>l.IsRoot).ToList();
}

I'm accepting the odata container generated by the T4 template as a parameter for the constructor in order to be able to Mock it somehow.

Unit test, here's where I'm lost:

    [TestMethod]
    public void LevelsVMConstructorTest()
    {
        List<Level>levels=new List<Level>();
        levels.Add(new Level(){Id=1,LevelId=1,Name="abc",IsRoot=True});
        IQueryable<Level>levelsIQ=levels.AsQueryable<Level>();

        //?
        var defaultContainerMock=new Mock<DefaultContainer>();
        defaultContainerMock.Setup(m=>m.Levels).Returns( I DON'T KNOW );


        //I want to get here
        LevelViewer lv = new LevelViewer(defaultContainerMock.Object);
        Assert.IsTrue(lv.GetRootLevels().Any());
    }

So in this unit test I only want to test the logic inside the GetRootLevels method, I don't want to make an integration test or a self hosting service, I just want to test the method with in-memory data.

How do I mock the OData client generated class which is actually a DataServiceContext class?

(I'm using Moq, but it can be anything)

Aucun commentaire:

Enregistrer un commentaire