I am developing a system in c# where, for specific reasons, we are using Entity Framework and Dapper: in some methods, we use Dapper and in other ones, we use Entity Framework.
We need to develop now some unit tests. I've been reading some approaches to mock a database to unit tests. However, most approaches seem specific to EF or Dapper.
Can you suggest a good approach where I can mock a database, simultaneously, to run unit tests that use EF AND Dapper?
For example: in a specific test, I will get a data using Dapper, then use this data to get another data using EF.
Thank you in advance.
One option that requires a test database is using dbsafe. https://github.com/dbsafe/dbsafe It has a NuGet package as well.
"Tests can be reused if the implementation or the technology used by the DAL changes."
dbsafe provides methods for populating a database, executing SQL commands, and comparing expected data against actual data.
It uses one or more xml input files with SQL scripts and datasets.
<?xml version="1.0" encoding="utf-8" ?> <dbTest> <scripts> <script name="delete-products"> DELETE [dbo].[Product]; </script> <script name="delete-categories"> DELETE [dbo].[Category]; </script> </scripts> <datasets> <dataset name="categories" setIdentityInsert="true" table="Category"> <data> <row Id="1" Name="category-1" /> <row Id="2" Name="category-2" /> <row Id="3" Name="category-3" /> </data> </dataset> <dataset name="suppliers" setIdentityInsert="true" table="Supplier"> <data> <row Id="1" Name="supplier-1" ContactName="contact-name-1" ContactPhone="100-200-0001" ContactEmail="firstname.lastname@example.org" /> <row Id="2" Name="supplier-2" ContactName="contact-name-2" ContactPhone="100-200-0002" ContactEmail="email@example.com" /> <row Id="3" Name="supplier-3" ContactName="contact-name-3" ContactPhone="100-200-0003" ContactEmail="firstname.lastname@example.org" /> </data> </dataset> </datasets> </dbTest>
The elements are SQL commands that can be executed any time during the test. E.g. cleaning tables, selecting actual data.
The elements contain data that can be used to populate a table or as the expected data.
dbsafe supports writing unit tests using the AAA (Arrange, Act, Assert) pattern.
Arrange initializes objects and sets the value of the data that is passed to the method under test.
Method ExecuteScripts can be used to execute scripts to delete old records. Method LoadTables can be used to populate tables.
Act invokes the method under test with the arranged parameters.
Assert verifies that the action of the method under test behaves as expected.
Method AssertDatasetVsScript can be used to compare expected data vs. actual data in the database.