How to unit test what is configured in the overridden OnModelCreating

I am using Entity Framework 6, and in my context I have an overridden OnModelCreating method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

Inside the method, I configured the database configuration. I would like to check what is configured. For example, I have the following code:

modelBuilder.HasDefaultSchema("public");

I would like to have a unit test that checks that HasDefaultSchema with the value of the parameter "public" is being called.

Or, as in the following example, I would like to verify that the HasMany and WithMany methods of the UserGroup entity are called:

 modelBuilder.Entity<UserGroup>()
             .HasMany<User>(g => g.Users)
             .WithMany(u => u.Groups)
             .Map(ug =>
                  {
                     ug.MapLeftKey("GroupId");
                     ug.MapRightKey("UserId");
                     ug.ToTable("UserGroupMembers");
                  });

Please inform. Thanks

+5
source share
4 answers

You can create a stub for you DbContext, which is an explicit call OnModelCreatingand check the statusDbModelBuilder

public class TestableMyDbContext : MyDbContext
  {
    public void TestModelCreation(DbModelBuilder model)
    {
        OnModelCreating(model);
        // check your model an throw an exception if invalid
    }
  }

TestMethod

[TestMethod]
public void Should_Initialize_Context()
{
  try
  {
    var context = new TestableMyDbContext();
  context.TestCallback(new DbModelBuilder());
  }
  catch (Exception ex)
  {
    Assert.Fail(ex.Message);
  }     
}
0

vappolinario, Mock<DbModelBuilder> TestableDbContext, , .

Moq xUnit

[Fact]
public void MyContext_HasCorrectDefaultSchema()
{
   var mockModel = new Mock<DbModelBuilder>();
   var context = new TestableMyContext();

   context.TestOnModelCreation(mockModel.Object);

   mockModel.Verify(m => m.HasDefaultSchema("public"), Times.Once());
}
0

.Net Core. DbContext, DataAnnotation, EF (, ).

NotMapped NotMapped OData NotMapped NotMapped $select, NotMapped EF , OData.

TestDbContext ModelDbContext (, , DbContextBase DbContextBase EF Ignore), ModelBuilder .

    public class TestDbContext : ModelDbContext
    {
      public ModelBuilder ModelBuilder { get; private set; }

      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
        base.OnModelCreating(modelBuilder);
        this.ModelBuilder = modelBuilder;
      }
    }

, :

. EF, , Ignored. , , EF .

    [Fact]
    public void OnModelCreatingTest()
    {
      // Arrange
      DbContextOptionsBuilder<ModelDbContext> builder = new DbContextOptionsBuilder<ModelDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString());
      var context = new TestDbContext(builder.Options);

      // Act
      // hit the entities to force the model to build
      var testEntity = context.ExampleEntities.FirstOrDefault();
      // use reflection to dig into EF internals
      var builderProperty = typeof(EntityTypeBuilder).GetProperty(
          "Builder",
          System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

      // Assert
      // validate that the extra ExampleEntity fields are ignored in EF (based on their data annotation)
      context.ModelBuilder.Entity(
        typeof(ExampleEntity),
        b =>
        {
          InternalEntityTypeBuilder baseBuilder = (InternalEntityTypeBuilder)builderProperty.GetValue(b);
          Assert.True(baseBuilder.IsIgnored("Property1", ConfigurationSource.Convention));
          Assert.True(baseBuilder.IsIgnored("Property2", ConfigurationSource.Convention));
        });
    }
0

, :

[TestMethod]
public void Should_Initialize_Context()
{
    try
    {
        var context = new MyDbContextContext("blah");
        context.Database.Initialize(false);

    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
    }
}
0

Source: https://habr.com/ru/post/1609292/


All Articles