Skip to content

Instantly share code, notes, and snippets.

@dmdeluca
Created October 5, 2021 05:04
Show Gist options
  • Save dmdeluca/2e431215290cf3a0ee500f298d20cddf to your computer and use it in GitHub Desktop.
Save dmdeluca/2e431215290cf3a0ee500f298d20cddf to your computer and use it in GitHub Desktop.
Minimal reader interface for a data access layer
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
}
}
using System;
public interface IRead<T>
{
U Read<U>(Func<IQueryable<T,U>> queryFunction);
}
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);
}
}
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