Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/neurospeech/ef-core-localdb-mock
Entity Framework Mocking using SQL Server LocalDB
https://github.com/neurospeech/ef-core-localdb-mock
Last synced: about 2 months ago
JSON representation
Entity Framework Mocking using SQL Server LocalDB
- Host: GitHub
- URL: https://github.com/neurospeech/ef-core-localdb-mock
- Owner: neurospeech
- License: gpl-3.0
- Created: 2017-11-10T11:30:16.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-02-01T10:22:40.000Z (almost 6 years ago)
- Last Synced: 2024-10-07T00:35:12.873Z (3 months ago)
- Language: C#
- Size: 24.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[![NuGet](https://img.shields.io/nuget/v/NeuroSpeech.EFCore.Mock.svg?label=NuGet)](https://www.nuget.org/packages/NeuroSpeech.EFCore.Mock)
# ef-core-localdb-mock
Entity Framework Mocking using SQL Server LocalDB```c#
// Assuming you have `AppDbContext` as your EF DbContext in side your actual application project
// For test purposes, you will have to use AppDbTestContext
// or you can use AppDbTestContext as dependency in your DI container
public class AppDbTestContext : ShopContext
{// this is important
// since databases are dynamically created and destroyed
// MockDatabaseContext.Current.ConnectionString contains
// correct database for current test context// MockDatabaseContext.Current will work correctly with async await
// without worrying about passing contextpublic AppDbTestContext(DbContextOptions options): base(options)
{}
public AppDbTestContext(): base(Create(MockDatabaseContext.Current.ConnectionString))
{}
public AppDbTestContext(string cnstr) : base(Create(cnstr)) {
}
public static DbContextOptions Create(string connectionString) {
DbContextOptionsBuilder builder = new DbContextOptionsBuilder();
builder.UseSqlServer(connectionString);
return builder.Options;
}
}public abstract class BaseTest :
MockSqlDatabaseContext
{public BaseTest(ITestOutputHelper writer)
{
this.Writer = writer;
}protected override void DumpLogs()
{
this.Writer.WriteLine(base.GeneratedLog);
}public ITestOutputHelper Writer { get; private set; }
public AppDbTestContext CreateContext()
{
AppDbTestContext db = new AppDbTestContext(ConnectionString);
db.Database.EnsureCreated();
Seed(db);
return db;
}public void Seed(AppDbTestContext db) {
db.Products.Add(new Product {
Name = "a"
});db.SaveChanges();
DoNotDelete = true;
}
}
```Test Case
```c#
public class DbTest : BaseTest {
[Fact]
public void Test1() {
using(var db = CreateContext()) {
// do test here...
}
// after this test is finished, database will be deleted automatically
// if you want to prevent deletion of database to investigate anything
// uncomment following
// DoNotDelete = true;
}
}```