JonPSmith / EfCore.TestSupport

Tools for helping in unit testing applications that use Entity Framework Core
https://www.thereformedprogrammer.net/new-features-for-unit-testing-your-entity-framework-core-5-code/
Other
352 stars 53 forks source link

Comparison fails for a default value with the default C# value #29

Closed davisnw closed 4 years ago

davisnw commented 4 years ago

Tested using EfCore.TestSupport nuget package 3.1.0

If entity framework is configured to have a Sql default that is the same as the C# default(T), then comparison incorrectly fails with an error similar to:

DIFFERENT: FooEntity->Property 'MyNumberWithDefault', default value sql. Expected = 0, found = <null>
DIFFERENT: FooEntity->Property 'MyNumberWithDefault', value generated. Expected = OnAdd, found = Never

Duplication:

    public class FooTest
    {
        public class FooEntity
        {
            [Key]
            public int Id { get; set; }

            public int MyNumberWithDefault { get; set; }
        }

        public class FooContext : DbContext
        {
            public FooContext(DbContextOptions dbContextOptions) : base(dbContextOptions) { }

            public DbSet<FooEntity> FooEntity { get; set; }

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

                modelBuilder.Entity<FooEntity>()
                    .Property(x => x.MyNumberWithDefault)
                    //NOTE: Change this to any other value besides 0, and the test passes
                    .HasDefaultValue(0);
            }
        }

        [Fact]
        public async Task ShouldAllowDefaultDefaultValue()
        {
            //----- Arrange -----//
            var dbContextOptions = new DbContextOptionsBuilder<FooContext>().UseSqlServer(this.GetUniqueDatabaseConnectionString());

            using (var fooContext = new FooContext(dbContextOptions.Options))
            {
                await fooContext.Database.EnsureDeletedAsync();
                await fooContext.Database.EnsureCreatedAsync();
            }

            //----- Act -----//
            var config = new CompareEfSqlConfig();

            var comparer = new CompareEfSql(config);

            var hasErrors = comparer.CompareEfWithDb(new FooContext(dbContextOptions.Options));

            //----- Act -----//
            Assert.False(hasErrors, comparer.GetAllErrors);
        }
    }
JonPSmith commented 4 years ago

See my comment on issue #28.