DD.WellWorkover.Cloud/AsbCloudWebApi.Tests/TestHelpter.cs

61 lines
2.3 KiB
C#
Raw Normal View History

2022-11-15 17:44:48 +05:00
using AsbCloudDb.Model;
2022-01-09 11:46:27 +05:00
using Microsoft.EntityFrameworkCore;
2022-11-15 17:44:48 +05:00
using Moq;
using System.Collections.Generic;
using System.Linq;
2022-01-09 11:46:27 +05:00
namespace AsbCloudWebApi.Tests
{
internal static class TestHelpter
{
2022-06-20 12:43:59 +05:00
// Попробовать когда-нибудь https://github.com/MichalJankowskii/Moq.EntityFrameworkCore
2022-11-15 17:44:48 +05:00
public static AsbCloudDbContext MakeRealTestContext()
2022-01-09 11:46:27 +05:00
{
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
2022-06-20 12:43:59 +05:00
//.UseInMemoryDatabase(System.Guid.NewGuid().ToString())
//.ConfigureWarnings(configBuilder =>
// configBuilder.Ignore(InMemoryEventId.TransactionIgnoredWarning))
2022-01-09 11:46:27 +05:00
.UseNpgsql("Host=localhost;Database=tests;Username=postgres;Password=q;Persist Security Info=True;Include Error Detail=True")
.Options;
var context = new AsbCloudDbContext(options);
2022-06-20 12:43:59 +05:00
//context.Database.EnsureDeleted();
2022-02-21 12:04:26 +05:00
context.Database.EnsureCreated();
2022-01-09 11:46:27 +05:00
return context;
}
2022-11-15 17:44:48 +05:00
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;
}
2022-01-09 11:46:27 +05:00
}
}