Search code examples
c#unit-testingtestingassertxunit

Data preparation for Unit test - C#


I am writing unit test/Component test using Entity Framework Core InMemory Provider.

When I write unit test, I came across with the following question.

I have the following two BL/DL methods.

  1. ToCreate
  2. ToGet

So when I write a unit test, I need to create some sample data for the unit test.

When I write a unit test for ToGet method, can I use ToCreate (BL method) to create sample data or When I write a unit test for ToCreate, Can I use ToGet method to check the created data? Is that a correct choice?

Referred the following to create a unit test: https://www.youtube.com/watch?v=ddrR440JtiA


Solution

  • You shouldn't verify that ToCreate persist data by using ToGet or ToGet by creating data through ToCreate. The reason is that your UT is not isolated and you are not verifying one behavior. Also your UT can pass in the cases where it shouldn't.

    What you should do: For each one of the methods create test cases, then for each test case create a UT and if there is an interaction with the DB context verify that the interaction occurred in the right way.

    For instance successfully persist one object:

    [Fact]
    public void ToCreate_Persist_One_Oblect(){
       //arrange:
       var sut = new Repository(context);
    
       //act
       sut.ToCreate(new XYzClass(){
           ... some properties
       });
    
       //assert:
       var newlyCreatedXyz = context.XYZ.FirstOfDefualt(/*get the item*/);
       Assert.NotNull(newlyCreatedXyz);
       /*Then asset the properties*/
    }
    

    If you are going to use a mocking framework instead of in memory DB then you can mock the DbContext and verify interaction.