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?

.NET 9のユニットテストプロジェクトでDbContextを差し替える

Posted at

こんにちは。

テックリードのTerukiです。

今回は軽めの記事ですが、.NET 8から.NET 9にアップデートする際にハマったことがあるのでその紹介です。

DbContextを差し替える

ユニットテストをASP.NET Coreなどのプロジェクトに対して実行したい場合、データベースをテスト用のものに差し替えたくなります。

リポジトリパターンとかでガチガチに作っておけばそのリポジトリ自体をモックしてしまえばこのようなことはする必要もありませんが、毎回メソッドを書くのはまあまあ面倒で悩みどころです。

DbContextをテスト用のものに差し替えればモックせずにテストデータを注入できるので差し替えたいわけですね。

.NET 8の場合

ASP.NET Coreにはテスト用にWebApplicationFactoryという便利なものがあります。

公式ドキュメント的にはここにあります。

builder.ConfigureServices(services => {
    // DbContextをインメモリDBに変更する
    services.Remove(services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ApplicationDbContext>))!);
    services.AddDbContext<OhmyteethDbContext>(options => {
        options.UseInMemoryDatabase("TestingDatabase");
    });
});

本当はSQLiteのものが良いですが、訳あってInMemoryDatabaseにしています。

SQLiteでも問題ないプロジェクトではSQLiteのほうが良いかと思います。

.NET 9の場合

.NET 9にすると、DIコンテナからRemoveしないといけないインターフェースが増えます。

builder.ConfigureServices(services => {
    // DbContextをインメモリDBに変更する
    services.Remove(services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ApplicationDbContext>))!);
    services.Remove(services.SingleOrDefault(d => d.ServiceType == typeof(IDbContextOptionsConfiguration<OhmyteethDbContext>))!); // これを追加
    services.AddDbContext<OhmyteethDbContext>(options => {
        options.UseInMemoryDatabase("TestingDatabase");
    });
});

これで.NET 9でも問題なく動きます。


これを書いた当時はエラー内容から頑張って特定したのですが、今はもうドキュメントに記載がありました:sob:

今更気づいてしまってちょっとショックですが、誰かの役に立てば良いなと。

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?