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

55 lines
2.0 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-18 16:13:32 +05:00
using Microsoft.Extensions.Caching.Memory;
using MockQueryable.Moq;
2022-11-15 17:44:48 +05:00
using Moq;
using System;
2022-11-15 17:44:48 +05:00
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
2022-01-09 11:46:27 +05:00
namespace AsbCloudWebApi.Tests
{
internal static class TestHelpter
{
2022-11-18 16:13:32 +05:00
public static IMemoryCache MemoryCache = new MemoryCache(new MemoryCacheOptions());
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>()
.UseNpgsql("Host=localhost;Database=tests;Username=postgres;Password=q;Persist Security Info=True;Include Error Detail=True")
.Options;
var context = new AsbCloudDbContext(options);
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 mockDbSet = dbSetData
.ToList()
.AsQueryable()
.BuildMockDbSet();
2022-11-15 17:44:48 +05:00
contextMock.Setup(o => o.Set<T>())
.Returns(mockDbSet.Object);
2022-11-15 17:44:48 +05:00
var dbSetProperty = typeof(IAsbCloudDbContext)
.GetProperties()
.FirstOrDefault(p => p.PropertyType.IsPublic && p.PropertyType == typeof(DbSet<T>));
if (dbSetProperty is not null)
{
// https://learn.microsoft.com/ru-ru/dotnet/api/system.linq.expressions.expression?view=net-7.0
var objParameterExpr = Expression.Parameter(typeof(IAsbCloudDbContext), "instance");
var propertyExpr = Expression.Property(objParameterExpr, dbSetProperty);
var expression = Expression.Lambda<Func<IAsbCloudDbContext, DbSet<T>>>(propertyExpr, objParameterExpr);
contextMock.SetupGet(expression).Returns(mockDbSet.Object);
}
2022-11-15 17:44:48 +05:00
return contextMock;
}
2022-01-09 11:46:27 +05:00
}
}