2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Entity Framework core関連の処理をIn Memory DBを利用してテストする

Last updated at Posted at 2018-05-16

#環境
Asp.Net Core 2.0.8
.Net Core 2.0
Entity Framework core 2.0.2
mssqllocaldb
MSTest

#プロダクトコード
##DataModelを作成

User.cs


    public partial class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsEnabled { get; set; }
    }

##DBContextを作成

HogeDbContext.cs

    public partial class HogeDbContext : DbContext
    {
       public virtual DbSet<User> User { get; set; }
       
       public HogeDbContext(DbContextOptions<HogeDbContext> option) : base(option) { }
    }

##DB ContextをDIコンテナに登録

Start.cs
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<HogeDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();
        }

##appsettings.JsonにDB接続文字列を設定

appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Hoge;Trusted_Connection=True;"
  }
}

##テスト対象

HogeLogic.cs
    public interface IUserlogic
    {
        IEnumerable<User> Get(); 
    }

    public class UserLogic
    {
        private HogeDbContext _dbContext;

        public UserLogic(HogeDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IEnumerable<User> Get()
        {
            return _dbContext.User.Where(u => u.IsEnabled);
        }
    }

#テストコード

UserLogicTests.cs
    [TestClass]
    public class UserLogicTests
    {

        [ClassInitialize]
        public static void ClassInitialize(TestContext testContext)
        {
            var options = new DbContextOptionsBuilder<HogeDbContext>()
                .UseInMemoryDatabase(databaseName: "Hoge")
                .EnableSensitiveDataLogging()
                .Options;
            using(var context = HogeDbContext(options))
            {
                context.User.Add(new User { Id = 1, Name="TestName1", IsEnabled = true});
                context.User.Add(new User { Id = 2, Name="TestName2", IsEnabled = false});
                context.SaveChanges();
            }
        }

        [TestMethod]
        public void 正常系_Get()
        {
            // arrange
            var options = new DbContextOptionsBuilder<HogeDbContext>()
                .UseInMemoryDatabase(databaseName: "Hoge")
                .EnableSensitiveDataLogging()
                .Options;

            
            using(var context = HogeDbContext(options))
            {
                // act
                var target = new UserLogic(context)
                var result = target.Get();                

                // assert
                Assert.IsNotNull(result);
                Assert.AreEqual(1, result.Count());
                Assert.IsTrue(result.Any(r => r.Id == 1 && r.Name == "TestName1"));
            }
        }
    }

In Memory DBを利用するように設定したDbContextOptionをコンスタントに渡すことで、
テスト時にIn Memory DBを利用できる。

DIコンテナ利用しない場合はDbContextのコンストラクタで良しなにすれば同様に
In Memory DBがテストで利用できる。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?