Created
October 5, 2021 05:04
-
-
Save dmdeluca/2e431215290cf3a0ee500f298d20cddf to your computer and use it in GitHub Desktop.
Minimal reader interface for a data access layer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Garbage | |
{ | |
public class Garbage | |
{ | |
public int GarbageId { get; set; } | |
public string Name { get; set; } | |
public GarbageType Type { get; set; } | |
} | |
public enum GarbageType | |
{ | |
Cardboard, | |
Plastic, | |
Glass, | |
Code | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public interface IRead<T> | |
{ | |
U Read<U>(Func<IQueryable<T,U>> queryFunction); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.EntityFrameworkCore; | |
using System; | |
public class Read<T> : IRead<T> | |
{ | |
private readonly DbContext _dbContext; | |
public Read(DbContext dbContext) | |
{ | |
_dbContext = dbContext; | |
} | |
public U Read<U>(Func<IQueryable<T,U>> queryFunction) | |
{ | |
var set = _dbContext.Set<T>(); | |
return queryFunction(set); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using AutoFac.Extras.Moq; | |
using XUnit; | |
using Moq; | |
public namespace Tests | |
{ | |
public class ReadTest | |
{ | |
[Fact] | |
public void Read_IsSimpleAndMockable() | |
{ | |
using var am = AutoMock.GetLoose(); | |
var mock = am.Mock<IRead<Garbage>>(); | |
// abstract away all queryable functions as we only care about the return type to close the loop. | |
mock.Setup(x => x.Read(It.IsAny<Func<IQueryable<Garbage>, Task<int>>>())) | |
.ReturnsAsync(10); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment