DD.WellWorkover.Cloud/AsbCloudWebApi.Tests/TestHelpter.cs
2022-11-15 17:46:58 +05:00

61 lines
2.3 KiB
C#

using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Moq;
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudWebApi.Tests
{
internal static class TestHelpter
{
// Попробовать когда-нибудь https://github.com/MichalJankowskii/Moq.EntityFrameworkCore
public static AsbCloudDbContext MakeRealTestContext()
{
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
//.UseInMemoryDatabase(System.Guid.NewGuid().ToString())
//.ConfigureWarnings(configBuilder =>
// configBuilder.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.UseNpgsql("Host=localhost;Database=tests;Username=postgres;Password=q;Persist Security Info=True;Include Error Detail=True")
.Options;
var context = new AsbCloudDbContext(options);
//context.Database.EnsureDeleted();
context.Database.EnsureCreated();
return context;
}
public static Mock<IAsbCloudDbContext> AddDbSetMock<T>(this Mock<IAsbCloudDbContext> contextMock, IEnumerable<T> dbSetData)
where T : class
{
var dbSetMock = MakeDbSetMock(dbSetData);
contextMock.Setup(o => o.Set<T>())
.Returns(() => dbSetMock.Object);
return contextMock;
}
public static Mock<DbSet<T>> MakeDbSetMock<T>()
where T : class
{
var dbSetData = new List<T>();
return MakeDbSetMock(dbSetData);
}
public static Mock<DbSet<T>> MakeDbSetMock<T>(IEnumerable<T> dbSetData)
where T : class
{
var dbSetDataQueriable = dbSetData
.ToList()
.AsQueryable();
Mock<DbSet<T>> dbSetMock = new();
dbSetMock.As<IQueryable<T>>().Setup(o => o.Provider).Returns(() => dbSetDataQueriable.Provider);
dbSetMock.As<IQueryable<T>>().Setup(o => o.Expression).Returns(() => dbSetDataQueriable.Expression);
dbSetMock.As<IQueryable<T>>().Setup(o => o.ElementType).Returns(() => dbSetDataQueriable.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(o => o.GetEnumerator()).Returns(() => dbSetDataQueriable.GetEnumerator());
return dbSetMock;
}
}
}