Base solution for your next web application
Open Closed

Unit test on service that uses Dbcontext instead of repository #8945


User avatar
0
MellowoodMedical created

Hi,

Currently we have a migration service in our project, which is a recurring job, and what it does is keep track of of some dbsets in dbcontext A and try to update some dbsets in another dbcontext B. Right now we want to write unit test for this migration service but kind of stuck. Here is our issues:

  1. There is only public method in our migration service, but it returns nothing(or just Task). So that means we can not simply call the method and assert(test) what it returns. Is there a way to test the result base on the dbcontext(or dbset) level?
  2. We use dbcontexts(2 dbcontexts to be exactly) to implement this method, one dbcontext is needed to be initialized in the constructor. I try to use Moq to mock the dbcontext and pass it to contructor, but it failed on initialization.

Any suggestion on how i need to change my unit test or even the original service?

Thanks


3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @MellowoodMedical

    Are you trying to background job or the class it uses to do the operation you want ? Mosf of the time, it is better to create a class and use it in both background job and test classes.

    For your questions;

    1. You can access the DbContexes using WithDbContext methods in your test methods.
    2. You can mock IDbContextProvider<YourDbContext> for this.
  • User Avatar
    0
    MellowoodMedical created

    Hi,

    Yes you are right and the background job is a class.

    I try to use IDBContextPorvider and the contructor does create succesfully by passing mockMyDbContextProvider.Object.GetDbContext() as the parameter. Now i am confused how to actually create fake datas inside the dbcontext and pass it down the road?

               var mockMyDbContext = new Mock<MyDbContext>();
                List<Tenant> tenants = GetTenants();
                var mockTenantsSet = new Mock<DbSet<Tenant>>();
                mockMyDbContext.Setup(m => m.Tenants).Returns(GetQueryableMockDbSet<Tenant>(tenants));
    
                List<Role> roles = GetRoles();
                var mockRolesSet = new Mock<DbSet<Role>>();
                mockMyDbContext.Setup(m => m.Roles).Returns(GetQueryableMockDbSet<Role>(roles));
                return mockMyDbContext;
    

    I used the above code to generate the fake data in my mockdbcontext and i am kind of confused how to combine it with the idbcontextprovider and pass it to the method that i want to test?

    Thanks

  • User Avatar
    1
    ismcagdas created
    Support Team

    Hi,

    You can return your Mock DbContext like below;

    mockMyDbContextProvider.Object.GetDbContext().Returns(mockMyDbContext)