首页 > 解决方案 > EF Core, EF 6 and the different testing methods

问题描述

Currently i am refactoring test for my context methods to not need a real database anymore. I use Ef Core.

So i read through the Microsoft documentation how to test context methods. I found the documentation for EF6 testing first and read the one for EfCore after.

Here are the links:

What i found interesting is that there are different best practices for EF6 and EF Core.

For EF6 Microsoft advises to use Mocking contexts with Moq or writing own test doubles. So both times mocking the context.

For EF Core Microsoft advises to use Sqlite or the built in InMemory database.

Mocking the context with Moq seems pretty reasonably for me. I just want to test the functionality of the methods. I have to do integration test anyways afterwards. Why is it not in the recommended ways for EF Core anymore? And more generally what are the advantages or problems with the different methods?

标签: c#entity-frameworkunit-testing.net-coreentity-framework-core

解决方案


仔细看看同一篇文章中的以下引用......

SQLite 内存模式允许您针对行为类似于关系数据库的提供程序编写有效的测试。

这为您提供了持续不变的测试数据,也为您提供了关系数据库问题和行为。它更接近实际的现实生活场景。

另一方面,Mocking 为您提供了一个实现,您可以在其中更改与任何其他模型的关系,因此它更加通用。

由于 EF 用于 db 并且您正在为 EF 进行测试,因此使用第一个选项非常有意义。通常情况下,您甚至不需要测试基因库等琐碎的操作

确保在更高级别(使用存储库的类等)上进行测试时,您使用模拟,因为您想模拟与具体实现没有也不应该有任何耦合的接口。


推荐阅读