Unit testing generic htmlHelper methods with nunit - unit-testing

I'm new to nUnit and I've been tasked with creating unit tests for some htmlhelper extension methods.
How should I go about creating a unit test for the following method?
public static MvcHtmlString EnumDropDownListForOrderBy<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, bool orderById, string firstElement = null, object htmlAttributes = null)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = values.Select(value => new SelectListItem()
{
Text = value.GetAttributeFrom<DescriptionAttribute>(value.ToString()).Description,
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
});
IEnumerable<SelectListItem> itemsFiltered = items.Where(e => !string.IsNullOrEmpty(e.Text)).AsEnumerable();
itemsFiltered = itemsFiltered.OrderBy(e => (orderById ? e.Text : e.Value));
return htmlHelper.DropDownListFor(
expression,
itemsFiltered,
firstElement,
htmlAttributes
);
}
Any help would be appreciated

Below is how you write a Unit Test for this. Note that since you have not specified that you use a Mock object framework I'm going to the poor man technique, which is the hand written stubs and mocks. There is also another helper method if you are using Moq.
It is important to note that, in order to simplify the code execution I have made couple of changes to your extension method, so the test would not fail unexpectedly. Checking for any unexpected behaver is a good defensive programming practice anyway.
Back to the tests.
SUT (System Under Test)
This is how the SUT (System Under Test) looks like and supporting types looks like. (Please feel free to modify to your need accordingly)
public static class MyHtmlHelper
{
public static MvcHtmlString EnumDropDownListForOrderBy<TModel, TEnum>
(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression,
bool orderById, string firstElement = null, object htmlAttributes = null,
Func<ModelMetadata> fromLambFunc = null)
{
ModelMetadata metadata =
ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items =
values.Select(value => new SelectListItem()
{
Text = GetText(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
});
IEnumerable<SelectListItem> itemsFiltered =
items.Where(e => !string.IsNullOrEmpty(e.Text)).AsEnumerable();
itemsFiltered = itemsFiltered.OrderBy(e => (orderById ? e.Text : e.Value));
return htmlHelper.DropDownListFor
(expression, itemsFiltered, firstElement, htmlAttributes);
}
private static Type GetNonNullableModelType(ModelMetadata metadata) {
return typeof (SomeEnum);
}
private static string GetText<TEnum>(TEnum value) {
return value.GetAttributeFrom<DescriptionAttribute>(value.ToString()) != null
? value.GetAttributeFrom<DescriptionAttribute>(value.ToString()).Description
: string.Empty;
}
}
public static class ExtensionMethodsAttr
{
public static T GetAttributeFrom<T>(this object instance, string propertyName)
where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return property != null ?
(T)property.GetCustomAttributes(attrType, false).First() : default(T) ;
}
}
public enum SomeEnum { A,}
Unit Tests
[TestFixture]
public class HtmlHelperTests
{
[Test]
public void EnumDropDownListForOrderBy_InvokeDropDownListFor_ReturnsExpectedSelectItemResult()
{
//Arrange
var expected = "<select id=\"Foo\" name=\"Foo\"></select>";
var fakeHtmlHelper = CreateHtmlHelperStaticStubs
(new ViewDataDictionary(new FakeViewModel() {Foo = SomeEnum.A}));
//var fakeHtmlHelper = CreateHtmlHelperUsingMoq
(new ViewDataDictionary(new FakeViewModel(){Foo = SomeEnum.A}));
//Act
var result = fakeHtmlHelper.EnumDropDownListForOrderBy
(model => model.Foo, It.IsAny<bool>(), null, null, null);
//Assert
Assert.AreEqual(expected, result.ToString());
}
private static HtmlHelper<FakeViewModel>
CreateHtmlHelperStaticStubs(ViewDataDictionary viewData)
{
var stubControllerContext = new ControllerContext(new FakeHttpContext(), new RouteData(), new FakeController());
var stubViewContext = new ViewContext(stubControllerContext, new FakeView(),
new ViewDataDictionary(new FakeViewModel() { Foo = SomeEnum.A }),
new TempDataDictionary(), new TextMessageWriter());
var fakeViewDataContainer = new FakeViewDataContainer();
fakeViewDataContainer.ViewData = viewData;
return new HtmlHelper<FakeViewModel>(stubViewContext, fakeViewDataContainer);
}
//Moq version
private static HtmlHelper<FakeViewModel>
CreateHtmlHelperUsingMoq(ViewDataDictionary viewData)
{
var stubControllerContext = new Mock<ControllerContext>();
stubControllerContext.Setup(x => x.HttpContext).Returns(new Mock<HttpContextBase>().Object);
stubControllerContext.Setup(x => x.RouteData).Returns(new RouteData());
stubControllerContext.Setup(x => x.Controller).Returns(new Mock<ControllerBase>().Object); ;
var stubViewContext = new Mock<ViewContext>();
stubViewContext.Setup(x => x.View).Returns(new Mock<IView>().Object);
stubViewContext.Setup(x => x.ViewData).Returns(viewData);
stubViewContext.Setup(x => x.TempData).Returns(new TempDataDictionary());
var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(v => v.ViewData).Returns(viewData);
return new HtmlHelper<FakeViewModel>(stubViewContext.Object, mockViewDataContainer.Object);
}
}
class FakeHttpContext : HttpContextBase
{
private Dictionary<object, object> _items = new Dictionary<object, object>();
public override IDictionary Items { get { return _items; } }
}
class FakeViewDataContainer : IViewDataContainer
{
private ViewDataDictionary _viewData = new ViewDataDictionary();
public ViewDataDictionary ViewData { get { return _viewData; } set { _viewData = value; } }
}
class FakeController : Controller { }
class FakeView : IView
{
public void Render(ViewContext viewContext, System.IO.TextWriter writer)
{
throw new NotImplementedException();
}
}
public class FakeViewModel {
public SomeEnum Foo { get; set; }
}

Related

Mock DBSet<T> and call AsQueryable method return an empty list

I use entity framework core 6, XUnit for testing, Moq 4.16.1
I have a List, Mock it as DBSet<T>, I call AsQueryable method on DBSet<T> then return a empty list. If i mock AsQueryable method on DBSet<T>, i will have a expected list. Can you tell me Why?
This is my code
public static class MockDbExtensions
{
public static Mock<DbSet<T>> MockDbSet<T>(this IQueryable<T> testData) where T : class
{
Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(new TestAsyncQueryProvider<T>(testData.Provider));
dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(testData.Expression);
dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(testData.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => testData.GetEnumerator());
dbSetMock.As<IAsyncEnumerable<T>>().Setup(m => m.GetAsyncEnumerator(default)).Returns(() => new TestAsyncEnumerator<T>(testData.GetEnumerator()));
return dbSetMock;
}
public static Mock<DbSet<T>> MockDbSet<T>(this IEnumerable<T> elements) where T : class
{
var testData = elements.AsQueryable();
return testData.MockDbSet();
}
public static Mock<DbSet<T>> MockDbSet<T>(this T[] elements) where T : class
{
var testData = elements.AsQueryable();
return testData.MockDbSet();
}
}
internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider
{
private readonly IQueryProvider _inner;
internal TestAsyncQueryProvider(IQueryProvider inner)
{
_inner = inner;
}
public IQueryable CreateQuery(Expression expression)
{
return new TestAsyncEnumerable<TEntity>(expression);
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
return new TestAsyncEnumerable<TElement>(expression);
}
public object Execute(Expression expression)
{
return _inner.Execute(expression);
}
public TResult Execute<TResult>(Expression expression)
{
return _inner.Execute<TResult>(expression);
}
public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
{
return new TestAsyncEnumerable<TResult>(expression);
}
public TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = new CancellationToken())
{
var expectedResultType = typeof(TResult).GetGenericArguments()[0];
var executionResult = ((IQueryProvider)this).Execute(expression);
return (TResult)typeof(Task).GetMethod(nameof(Task.FromResult))
.MakeGenericMethod(expectedResultType)
.Invoke(null, new[] { executionResult });
}
}
internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T>
{
public TestAsyncEnumerable(IEnumerable<T> enumerable)
: base(enumerable)
{ }
public TestAsyncEnumerable(Expression expression)
: base(expression)
{ }
public IAsyncEnumerator<T> GetEnumerator()
{
return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this);
}
internal class TestAsyncEnumerator<T> : IAsyncEnumerator<T>
{
private readonly IEnumerator<T> _inner;
public TestAsyncEnumerator(IEnumerator<T> inner)
{
_inner = inner;
}
public void Dispose()
{
_inner.Dispose();
}
public T Current => _inner.Current;
public Task<bool> MoveNext(CancellationToken cancellationToken)
{
return Task.FromResult(_inner.MoveNext());
}
public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(_inner.MoveNext());
public ValueTask DisposeAsync()
{
_inner.Dispose();
return new ValueTask();
}
}
public class ReportTemplateServiceTests
{
private List<ReportTemplateType> CreateReportTemplateTypes()
{
return new List<ReportTemplateType>
{
new ReportTemplateType { Id = new Guid("144013ED-2D77-4572-8AB4-483C66E4EF1D"), Name = "Financial statements", DisplayOrder = 3, CmsId = 101475, IsActive = true },
new ReportTemplateType { Id = new Guid("058F8F85-A735-48F3-B526-79855FFF1EB0"), Name = "Reports", DisplayOrder = 1, CmsId = 100473, IsActive = true },
new ReportTemplateType { Id = new Guid("69D55B31-69BB-4BBC-82F1-A707B484E99B"), Name = "Letters", DisplayOrder = 2, CmsId = 100474, IsActive = true },
new ReportTemplateType { Id = new Guid("19D2650B-CE8E-4B54-95D9-ACAFA5C1CE40"), Name = "Custom working papers", DisplayOrder = 4, CmsId = 101476, IsActive = true },
};
}
public async void CreateReportTemplateAsync_Success()
{
// Arrange
var reportTemplates = CreateReportTemplates().MockDbSet().Object;
var a = reportTemplates.AsQueryable().ToList(); // return empty list after call AsQueryable()
}
}
I mock AsQueryable method on DBSet<T>, i will have a expected list.

unit test for MediatR in .net6 with generic repo returns null repository

I am using MediatR for command query segregation.
I want to test the command method, my command method accept a clientappsetting model as an input .here you can see my whole handler and command code :
AddClientAppSettingCommandHandler : IRequestHandler<AddClientAppSettingCommand, AddClientAppSettingResponse>
{
private readonly ICurrentUserService _userService;
private readonly IRepository<ClientAppSettings> _repository;
public AddClientAppSettingCommandHandler(ICurrentUserService userService,
IRepositoryAccessor repositoryAccessor)
{
_userService = userService;
_repository = repositoryAccessor.GetRepository<ClientAppSettings>(_userService.CustomerIsin,
reThrowException: true, type: DatabaseType.Raven);
}
public async Task<AddClientAppSettingResponse> Handle(AddClientAppSettingCommand request,
CancellationToken cancellationToken)
{
var entity = new ClientAppSettings(_userService.CustomerIsin)
{
LightTheme = request.Setting.LightTheme,
Order = request.Setting.Order,
Notch = request.Setting.Notch,
PageSize = request.Setting.PageSize,
ApplyCommissionInPortfolio = request.Setting.ApplyCommissionInPortfolio,
UseClosingPriceInPortfolioTotalValue = request.Setting.UseClosingPriceInPortfolioTotalValue,
ShowNotifications = request.Setting.ShowNotifications,
NoSleep = request.Setting.NoSleep,
NoBalance = request.Setting.NoBalance,
DataTracker = request.Setting.DataTracker,
UserStatusBarToUp = request.Setting.UserStatusBarToUp,
PortfolioBasedOnLastPositivePeriod = request.Setting.PortfolioBasedOnLastPositivePeriod,
};
var cRepository = CacheableRepository<ClientAppSettings>.From(_repository);
var result = await cRepository.AddOrUpdateAsync(entity);
if (!result.IsSucceeded)
throw new EasyException(EasyException.DATABASE_EXCEPTION, result.Error);
return AddClientAppSettingResponse.Map(entity);
}
As you can see my handler has two dependencies ICurrentUserService , IRepositoryAccessor
My problem is IRepositoryAccessor when I run the test the repository object is null .
Here is my repository interface and imp ;
public interface IRepositoryAccessor
{
IRepository<TEntity> GetRepository<TEntity>(
string shard = "public",
DatabaseType type = DatabaseType.Raven,
Type inheritedRepository = null,
bool manualDisposing = false,
bool reThrowException=false) where TEntity : BaseEntity;
void CloseSession();
}
The imp :
public sealed class RepositoryAccessor : IRepositoryAccessor, IDisposable
{
private static readonly Dictionary<Type, object> FlyweightSqlGenerator = new();
private readonly List<IDisposable> _sessions = new();
private readonly ITracer _tracer;
private readonly IConfiguration _configuration;
public RepositoryAccessor(IConfiguration configuration, ITracer tracer = null)
{
_configuration = configuration;
_tracer = tracer;
}
public void CloseSession()
{
for (int i = 0; i < _sessions.Count; i++)
{
_sessions[i].Dispose();
}
_sessions.Clear();
}
public void Dispose() => CloseSession();
public IRepository<TEntity> GetRepository<TEntity>(
string shard = "public",
DatabaseType type = DatabaseType.Raven,
Type inheritedRepository = null,
bool manualDisposing = false,
bool reThrowException = false) where TEntity : BaseEntity
{
if (type == DatabaseType.Raven)
{
return GetRavenRepository<TEntity>(inheritedRepository, shard, manualDisposing, reThrowException);
}
else if (type == DatabaseType.Redis)
{
return new RedisRepository<TEntity>();
}
return GetSQLRepository<TEntity>(inheritedRepository, manualDisposing, reThrowException);
}
}
And here is my test :
[Fact]
public async void Test1()
{
//Arange
var mediator = new Mock<IMediator>();
var userservice = new Mock<ICurrentUserService>();
var repo = new Mock<IRepositoryAccessor>();
AddClientAppSettingCommand command = new AddClientAppSettingCommand(new domain.Entities.ClientAppSettings());
AddClientAppSettingCommandHandler handler = new AddClientAppSettingCommandHandler(userservice.Object,repo.Object);
//Act
var x = await handler.Handle(command, new System.Threading.CancellationToken());
}
And when I run the test with debug mode my repository is null :
I should define IAccessor and IRepository as a mock and setting up the Irepository for IAccessor as you can see :
var repoacc = new Mock<IRepositoryAccessor>();
var repo = new Mock<domain.Interfaces.IRepository<ClientAppSettings>>();
repoacc.Setup(i => i.GetRepository<ClientAppSettings>(It.IsAny<string>(), DatabaseType.Raven, null, false, true)).Returns(repo.Object);

xUnit ClaimsPrincipal mock and passing into controller User is null

I have been reading articles trying to figure this one out. Structured off of this article How to add claims in a mock ClaimsPrincipal. I am still getting a null user from my controller and test fails on a null object of User inside the controller.
BusinessController
[Route("api/[controller]")]
[ApiController]
public class BusinessController : ControllerBase
{
private readonly IGBusinessRepository businessRepository;
private readonly IPersonRepository personRepository;
private readonly IUserClaims userClaims;
public BusinessController(IGBusinessRepository businessRepository,
IPersonRepository personRepository,
IUserClaims userClaims)
{
this.businessRepository = businessRepository;
this.personRepository = personRepository;
this.userClaims = userClaims;
}
// GET api/<BusinessController>/5
[HttpGet("{id}")]
[Authorize]
public async Task<IActionResult> GetBusiness(Guid businessId)
{
var userGuid = userClaims.GetUserGuid(User.Claims);
var ownerId = await personRepository.GetPersonIdByGUID(userGuid);
var business = await businessRepository.GetBusinessById(businessId);
if(business != null && business.OwnerId == businessId)
{
return Ok(business);
}
return BadRequest("Bad business id or your not the owner");
}
UserClaims
public class UserClaims : IUserClaims
{
public string GetUserGuid(IEnumerable<Claim> claims)
{
var claimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
var guidClaim = claims.Where(c => c.Type == claimType).Select(s => s.Value).SingleOrDefault();
return guidClaim;
}
}
TestIdentity
public class TestIdentity : ClaimsIdentity
{
public TestIdentity(params Claim[] claims) : base(claims)
{
}
}
TestPrincipal
public class TestPrincipal : ClaimsPrincipal
{
public TestPrincipal(params Claim[] claims) : base(new TestIdentity(claims))
{
}
}
BusinessControllerTests
public class BusinessControllerTests
{
//Controller
private readonly Mock<IGBusinessRepository> mockBusinessRepository;
private readonly Mock<IPersonRepository> mockPersonRepository;
private readonly Mock<IUserClaims> mockUserClaims;
private BusinessController controller;
//Objects
private Guid id = Guid.NewGuid();
public BusinessControllerTests()
{
mockBusinessRepository = new Mock<IGBusinessRepository>();
mockPersonRepository = new Mock<IPersonRepository>();
mockUserClaims = new Mock<IUserClaims>();
controller = new BusinessController(mockBusinessRepository.Object, mockPersonRepository.Object, mockUserClaims.Object);
}
[Fact]
public async Task GetBussiness_NotBusinessOwner_ReturnsBadRequest()
{
//Arrange
var userGuidString = Guid.NewGuid().ToString();
var ownerId = Guid.NewGuid();
var userClaim = new TestPrincipal(new Claim("name", "user#domain.com"));
Thread.CurrentPrincipal = userClaim;
//mockUserClaims.Setup(repo => repo.GetUserGuid(userClaim)).Returns(userGuidString);
mockPersonRepository.Setup(repo => repo.GetPersonIdByGUID(userGuidString));
mockBusinessRepository.Setup(repo => repo.GetBusinessById(id)).ReturnsAsync(business);
//Act
var result = await controller.GetBusiness(id);
//Assert
Assert.IsType<BadRequestResult>(result);
}
private GobiezBusiness business = new GobiezBusiness()
{
Id = new MongoDB.Bson.ObjectId(),
BusinessId = Guid.NewGuid(),
Name = "Test",
Email = "Test#helpme.com",
Address = "123 A street",
State = "WA",
ZipCode = "12345",
PhoneNumber = "123-456-7890",
OwnerId = Guid.NewGuid()
};
}
The controller was not arranged correctly to be able to access the principal
// ... omitted for brevity
var userClaim = new TestPrincipal(new Claim("name", "user#domain.com"));
var httpContext = new DefaultHttpContext() {
User = userClaim;
};
//Controller needs a controller context to access HttpContext
var controllerContext = new ControllerContext() {
HttpContext = httpContext
};
//assign context to controller
BusinessController controller = new BusinessController(
mockBusinessRepository.Object,
mockPersonRepository.Object,
mockUserClaims.Object)
{
ControllerContext = controllerContext
};
//Act
var result = await controller.GetBusiness(id);
// ... omitted for brevity
The controller should also be created within the scope of the test being executed.
This line in the subject under test
//...
var userGuid = userClaims.GetUserGuid(User.Claims);
//...
Should now return the created TestPrincipal arranged in the test

How to Mock QueryMultiple using Moq.Dapper

I am writing unit test cases and I am successful in writing unit test case for Query. But I am failing to write unit test case for QueryMultiple.
For Query I am writing like this:
IEnumerable<ClientTestPurpose> fakeTestPurposes = new
List<ClientTestPurpose>()
{
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name1"},
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name2"},
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name3"}
};
_mock.SetupDapper(x => x.Query<ClientTestPurpose>(It.IsAny<string>(), null, null, true, null, null)).Returns(fakeTestPurposes);
var result = _libraryRepository.TestPurposes(clientModal.Id);
Assert.IsNotNull(result);
Assert.AreEqual(result.Count(), fakeTestPurposes.Count());
How to write for QueryMultiple:
using (var multi = _db.QueryMultiple(spName, spParams, commandType: CommandType.StoredProcedure))
{
var totals = multi.Read<dynamic>().FirstOrDefault();
var aggregates = multi.Read<StatusModel>();
var scripts = multi.Read<LibraryItemModel>();
var runs = multi.Read<RunSummaryModel>();
var filteredTotals = multi.Read<dynamic>().FirstOrDefault();
}
Apparently you use Moq.Dapper extenstions. Here is the code of SetupDapper and SetupDapperAsync method:
public static ISetup<IDbConnection, TResult> SetupDapper<TResult>(this Mock<IDbConnection> mock, Expression<Func<IDbConnection, TResult>> expression)
{
MethodCallExpression body = expression.Body as MethodCallExpression;
if ((body != null ? body.Method.DeclaringType : (Type) null) != typeof (SqlMapper))
throw new ArgumentException("Not a Dapper method.");
string name = body.Method.Name;
if (name == "Execute")
return (ISetup<IDbConnection, TResult>) DbConnectionInterfaceMockExtensions.SetupExecute(mock);
if (name == "ExecuteScalar")
return DbConnectionInterfaceMockExtensions.SetupExecuteScalar<TResult>(mock);
if (name == "Query" || name == "QueryFirstOrDefault")
return DbConnectionInterfaceMockExtensions.SetupQuery<TResult>(mock);
throw new NotSupportedException();
}
public static ISetup<IDbConnection, Task<TResult>> SetupDapperAsync<TResult>(this Mock<IDbConnection> mock, Expression<Func<IDbConnection, Task<TResult>>> expression)
{
MethodCallExpression body = expression.Body as MethodCallExpression;
if ((body != null ? body.Method.DeclaringType : (Type) null) != typeof (SqlMapper))
throw new ArgumentException("Not a Dapper method.");
if (body.Method.Name == "QueryAsync")
return DbConnectionInterfaceMockExtensions.SetupQueryAsync<TResult>(mock);
throw new NotSupportedException();
}
As you can see Moq.Dapper supports mocking only for Execute, ExecuteScalar, Query and QueryAsync methods. Therefore you probably get NotSupportedException on trying to mock QueryMultiple. To mock DB behavior you probably need introduce another level of abstraction first, as #TrueWill said in a comments. Here is just an example of idea how it can be in your case:
[Test]
public void DoSomethingWithQueryTest()
{
// Arrange
IEnumerable<ClientTestPurpose> fakeTestPurposes = new
List<ClientTestPurpose>
{
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name1" },
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name2" },
new ClientTestPurpose { PurposeID = 1, PurposeName = "Test Purpose name3" }
};
var mock = new Mock<ILibraryRepository>();
mock.Setup(x => x.TestPurposes(It.IsAny<int>())).Returns(fakeTestPurposes);
var logicService = new SomeLogicService(mock.Object);
// Act
var result = logicService.DoSomethingWithQuery(1);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(result.Count(), fakeTestPurposes.Count());
}
[Test]
public void DoSomethingWithQueryMultipleTest()
{
// Arrange
SomeAggregate fakeTestPurposes = new SomeAggregate();
var mock = new Mock<ILibraryRepository>();
mock.Setup(x => x.TestQueryMultiple()).Returns(fakeTestPurposes);
var logicService = new SomeLogicService(mock.Object);
// Act
var result = logicService.DoSomethingWithQueryMultiple();
// Assert
Assert.IsNotNull(result);
}
public interface ILibraryRepository
{
IEnumerable<ClientTestPurpose> TestPurposes(int id);
SomeAggregate TestQueryMultiple();
}
public class LibraryRepository : ILibraryRepository
{
private readonly IDbConnection _db;
public LibraryRepository(IDbConnection db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
public IEnumerable<ClientTestPurpose> TestPurposes(int id)
{
return _db.Query<ClientTestPurpose>("SQL here", new { id }, null, true, null, null);
}
public SomeAggregate TestQueryMultiple()
{
string spName = "SQL here";
var spParams = new { Id = 1 };
using (var multi = _db.QueryMultiple(spName, spParams, commandType: CommandType.StoredProcedure))
{
return new SomeAggregate
{
totals = multi.Read<dynamic>().FirstOrDefault(),
aggregates = multi.Read<StatusModel>(),
scripts = multi.Read<LibraryItemModel>(),
runs = multi.Read<RunSummaryModel>(),
filteredTotals = multi.Read<dynamic>().FirstOrDefault()
};
}
}
}
public class SomeAggregate
{
public IEnumerable<dynamic> totals { get; set; }
public IEnumerable<StatusModel> aggregates { get; set; }
public IEnumerable<LibraryItemModel> scripts { get; set; }
public IEnumerable<RunSummaryModel> runs { get; set; }
public IEnumerable<dynamic> filteredTotals { get; set; }
}
/// <summary>
/// Example logic server, that just returns results from repository
/// </summary>
public class SomeLogicService
{
private readonly ILibraryRepository _repo;
public SomeLogicService(ILibraryRepository repo)
{
_repo = repo;
}
public IEnumerable<ClientTestPurpose> DoSomethingWithQuery(int id)
{
return _repo.TestPurposes(id);
}
public SomeAggregate DoSomethingWithQueryMultiple()
{
return _repo.TestQueryMultiple();
}
}
The main idea is to hide all DB specific thing behind the ILibraryRepository and move all logic that you need to test to some logic server, that will receive repository as dependency. In order code in repository should be simple, obvious, contains all DB specific logic: connection, transaction, command, object-relation mapping, etc. And you don't need to cover this code with unt tests. However you do cover code of SomeLogicService with unit tests, because this is what you really need to test. You see Dapper extension method are rather low-level abstraction, that doesn't hide details of working with DB, they are just helpers. Hope it helps.

Where do you set the OrmLiteConfig.DialectProvider.NamingStrategy in a unit test?

I'm using both ORMLite and Dapper in a project and would like standardized on the naming conventions used by both ORMs. In order to do this I'd like to set the NamingStrategy as such:
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
and a unit test to verify
public class BorrowerUnitTests : IDisposable
{
private readonly ServiceStackHost appHost;
public BorrowerUnitTests()
{
//Set ORMLite to work with columns like ColumnLikeThis
// OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
appHost = new BasicAppHost(typeof(BorrowerServices).Assembly)
{
ConfigureContainer = container =>
{
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("LoanOrigination:Default"), PostgreSqlDialect.Provider));
container.RegisterAutoWiredAs<Repository, IRepository>();
container.RegisterAutoWired<BorrowerDomainService>();
}
}
.Init();
}
public void Dispose()
{
appHost.Dispose();
}
[Fact]
public void TestPostMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerCreate request = new BorrowerCreate();
request.FirstName = "Orm";
request.LastName = "Lite";
request.Email = "ormlite#servicestack.net";
var response = service.Post(request);
Assert.True(response.Id > 0, "Id retured from POST cannot be zero");
}
[Fact]
public void TestGetMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerGet request = new BorrowerGet();
request.Id = 1;
var response = service.Get(request);
Assert.Equal("ormlite#servicestack.net", response.Email);
}
[Fact]
public void TestPutMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerUpdate request = new BorrowerUpdate();
request.Id = 5;
request.FirstName = "MyFirstName2";
request.LastName = "MyLastName2";
request.Email = "MyEmail#Example.com";
var response = service.Put(request);
Assert.True(response.FirstName == "MyFirstName2", "FirstName is noth equal");
}
}
No matter where I put the NamingStrategy statement, I get a exception from the DialectProvider property of the OrmLiteConfig class, "You must set the singleton 'OrmLiteConfig.DialectProvider' to use the OrmLiteWriteExtensions"
Where's the proper place to set this property?
Thank you,
Stephen
You can just assign it to the DialectProvider you're using, e.g:
PostgreSqlDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();
The OrmLiteConfig.DialectProvider is a singleton that can either be set manually:
OrmLiteConfig.DialectProvider = PostgreSqlDialect.Provider;
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
Or implicitly with the new OrmLiteConnectionFactory() constructor, which to run, needs to resolved from the IOC:
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(...));
using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
}