I am attempting to mock out some of EF Core's functions.
Originally I was getting the following error
The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations.
After looking at this question it almost seems to work but i'm now getting the following:
System.ArgumentNullException : Value cannot be null.
Parameter name: source
at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable1 source, Expression1 predicate, CancellationToken cancellationToken)
at Ombi.Core.Rule.Rules.Search.RadarrCacheRule.d__2.MoveNext() in C:\Users\Jamie.Rees\Source\Repos\PlexRequests.Net\src\Ombi.Core\Rule\Rules\Search\RadarrCacheRule.cs:line 25
Here is the test code:
[Test]
public async Task Should_ReturnApproved_WhenMovieIsInRadarr()
{
var list = new List<RadarrCache>(){new RadarrCache
{
TheMovieDbId = 123
}}.AsQueryable();
var radarrMock = new Mock<DbSet<RadarrCache>>();
radarrMock.As<IAsyncEnumerable<RadarrCache>>()
.Setup(m => m.GetEnumerator())
.Returns(new TestAsyncEnumerator<RadarrCache>(list.GetEnumerator()));
radarrMock.As<IQueryable<RadarrCache>>()
.Setup(m => m.Provider)
.Returns(new TestAsyncQueryProvider<RadarrCache>(list.Provider));
radarrMock.As<IQueryable<RadarrCache>>().Setup(m => m.Expression).Returns(list.Expression);
radarrMock.As<IQueryable<RadarrCache>>().Setup(m => m.ElementType).Returns(list.ElementType);
radarrMock.As<IQueryable<RadarrCache>>().Setup(m => m.GetEnumerator()).Returns(() => list.GetEnumerator());
ContextMock.Setup(c => c.Set<RadarrCache>()).Returns(radarrMock.Object);
var request = new SearchMovieViewModel { Id = 123 };
var result =await Rule.Execute(request);
Assert.True(result.Success);
Assert.True(request.Approved);
}
This is the class under test:
public class RadarrCacheRule : BaseSearchRule, IRules<SearchViewModel>
{
public RadarrCacheRule(IOmbiContext ctx)
{
_ctx = ctx;
}
private readonly IOmbiContext _ctx;
public async Task<RuleResult> Execute(SearchViewModel obj)
{
if (obj.Type == RequestType.Movie)
{
// Check if it's in Radarr
var result = await _ctx.RadarrCache.FirstOrDefaultAsync(x => x.TheMovieDbId == obj.Id);
if (result != null)
{
obj.Approved =
true; // It's in radarr so it's approved... Maybe have a new property called "Processing" or something?
}
}
return Success();
}
}
Any idea how I am suppose to do this?
Related
I have this class called Handler, which is a MassTransit IConsumer:
public class Handler : IConsumer<ICommand>
{
private readonly IOrderRepository _orderRepository;
public Handler(IOrderRepository orderRepository)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
public async Task Consume(ConsumeContext<ICommand> context)
{
var command = context.Message;
var orderId = new OrderId(command.OrderId);
var order = await _orderRepository.FindOrderAsync(orderId, context.CancellationToken);
if (order is null)
{
await context.RespondAsync(CommandResponse.NotFound);
return;
}
order.Cancel();
await _orderRepository.SaveOrderAsync(order, context.CancellationToken);
await context.RespondAsync(CommandResponse.Submitted);
}
}
I have two unit tests for it. Here's the one that seems to work fine:
[TestMethod]
public async Task Consume_WithExistingOrderId_CancelsOrderAndSavesChangesAndReturnsSubmitted()
{
// Arrange
var mockConsumer = new Mock<IConsumer<ICommand>>();
var mockRepository = new Mock<IOrderRepository>();
var sut = new Handler(mockRepository.Object);
var mockCommand = new Mock<ICommand>();
var mockContext = new Mock<ConsumeContext<ICommand>>();
mockContext.Setup(x => x.Message).Returns(mockCommand.Object);
mockContext.Setup(x => x.RespondAsync(It.IsAny<CommandResponse>())).Returns(Task.CompletedTask);
var existingOrderId = new OrderId(Guid.NewGuid());
mockCommand.Setup(x => x.OrderId).Returns(existingOrderId.Value);
var order = GetTestOrder(existingOrderId);
mockRepository.Setup(x => x.FindOrderAsync(existingOrderId, It.IsAny<CancellationToken>())).ReturnsAsync(order);
// Act
await sut.Consume(mockContext.Object);
// Assert
mockRepository.Verify(x => x.SaveOrderAsync(order, It.IsAny<CancellationToken>()), Times.Once());
mockContext.Verify(x => x.RespondAsync(CommandResponse.Submitted), Times.Once());
order.IsCancelled.Should().BeTrue();
}
And here's the one that isn't doing what I expected:
[TestMethod()]
public async Task Consume_WithNonExistantOrderId_ReturnsNotFoundResponseAndDoesNotSave()
{
// Arrange
var mockRepository = new Mock<IOrderRepository>();
var sut = new Handler(mockRepository.Object);
var mockCommand = new Mock<ICommand>();
var mockContext = new Mock<ConsumeContext<ICommand>>();
mockContext.Setup(x => x.Message).Returns(mockCommand.Object);
mockContext.Setup(x => x.RespondAsync(It.IsAny<CommandResponse>())).Returns(Task.CompletedTask);
var nonExistantOrderId = new OrderId(Guid.NewGuid());
mockCommand.Setup(x => x.OrderId).Returns(nonExistantOrderId.Value);
mockRepository.Setup(x => x.FindOrderAsync(nonExistantOrderId, It.IsAny<CancellationToken>())).ReturnsAsync((Order?)null);
// Act
await sut.Consume(mockContext.Object);
// Assert
mockRepository.Verify(x => x.SaveOrderAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Never());
mockContext.Verify(x => x.RespondAsync(CommandResponse.NotFound), Times.Once());
}
Both unit tests require that the Handler calls the RespondAsync method of the MassTransit context exactly once. However, the second unit test doesn't pass, saying that the method was never called. I don't see why it was never called. When I debug into the method it appears to show the method is called.
I can't tell if my test is wrong or if my system under test is wrong. Can anybody see the problem please?
(Also, if anybody can see how to make my code more testable and my unit tests shorter and simpler that would also be appreciated.)
The problem is with the nonExistantOrderId and using that for the match in expectation.
mockRepository
.Setup(x => x.FindOrderAsync(nonExistantOrderId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Order?)null);
the mock expects to get that specific instance when the subject is being exercised but the subject initialized its own instance which causes the mock to not invoke the async call and exit the subject before that target line can be invoked.
This is why
mockRepository.Verify(x => x.SaveOrderAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Never());
supposedly passed verification, and
mockContext.Verify(x => x.RespondAsync(CommandResponse.NotFound), Times.Once());
failed since the subject code exited before reaching both members that are the targets of your verification.
Loosen the match using It.IsAny<OrderId>()
mockRepository
.Setup(x => x.FindOrderAsync(It.IsAny<OrderId>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Order?)null);
so that the mocked async call can be invoked and allow the code to flow to completion.
I have accepted Nkosi's answer because it solved the problem stated in the question. Thank you, Nkosi.
However, the resources that were provided by the MassTransit boss-man, #Chris Patterson, were helpful in making a better unit test altogether. That's why I'm posting this alternative answer. This answer rewrites the original unit test to use the MassTransit test harness, and I hope it helps somebody one day.
Chris's links have somehow disappeared from sight. However, I think he posted this:
https://www.youtube.com/watch?v=Cx-Mc0DCpfE&t=545s
And this:
https://masstransit-project.com/usage/testing.html
The rewritten method:
public interface ICommand
{
Guid OrderId { get; }
}
public record Command : ICommand
{
public Command(Guid orderId)
{
OrderId = orderId;
}
public Guid OrderId { get; }
}
public class Handler : IConsumer<ICommand>
{
private readonly IOrderRepository _orderRepository;
public Handler(IOrderRepository orderRepository)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
public async Task Consume(ConsumeContext<ICommand> context)
{
var command = context.Message;
OrderId orderId = new OrderId(command.OrderId);
var order = await _orderRepository.FindOrderAsync(orderId, context.CancellationToken);
if (order is null)
{
await context.RespondAsync(CommandResponse.NotFound);
return;
}
order.Cancel();
await _orderRepository.SaveOrderAsync(order, context.CancellationToken);
await context.RespondAsync(CommandResponse.Submitted);
}
}
The rewritten unit test class:
[TestClass()]
public class Handler_Tests
{
private static OrderId ExistingOrderId = new OrderId("d94108e4-1121-401a-a6ef-c7736054041d");
private static OrderId NonExistentOrderId = new OrderId("daaa72a0-8f8c-4a9b-b4ad-ebefbb6b5aa2");
private static CustomerId ExistingCustomerId = new CustomerId("5fbf40d8-c064-4821-8948-a520863e6242");
[TestMethod()]
public async Task Consume_WithExistingOrderId_CancelsOrderAndSavesChangesAndReturnsSubmitted2()
{
// Arrange
var harness = new InMemoryTestHarness();
var mockRepository = GetMockOrderRepository();
var sut = harness.Consumer(() =>
{
return new Handler(mockRepository.Object);
});
await harness.Start();
try
{
var requestClient = await harness.ConnectRequestClient<ICommand>();
var command = new Command(ExistingOrderId.Value);
// Act
var response = await requestClient.GetResponse<CommandResponse>(command, It.IsAny<CancellationToken>());
// Assert
mockRepository.Verify(x => x.SaveOrderAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Once());
response.Message.Result.Should().Be(CommandResponse.Results.Submitted);
}
finally
{
await harness.Stop();
}
}
[TestMethod()]
public async Task Consume_WithNonExistentOrderId_ReturnsNotFoundResponseAndDoesNotSave()
{
// Arrange
var harness = new InMemoryTestHarness();
var mockRepository = GetMockOrderRepository();
var sut = harness.Consumer(() =>
{
return new Handler(mockRepository.Object);
});
await harness.Start();
try
{
var requestClient = await harness.ConnectRequestClient<ICommand>();
var command = new Command(NonExistentOrderId.Value);
var response = await requestClient.GetResponse<CommandResponse>(command, It.IsAny<CancellationToken>());
mockRepository.Verify(x => x.SaveOrderAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Never());
response.Message.Result.Should().Be(CommandResponse.Results.NotFound);
}
finally
{
await harness.Stop();
}
}
private static Order GetTestOrder(OrderId orderId)
{
var orderItem = GetTestOrderItem();
return Order.Place(orderId, ExistingCustomerId, new[] { orderItem });
}
private static OrderItem GetTestOrderItem()
{
var productId = new ProductId(Guid.NewGuid());
var price = new Price(1, PurchaseCurrency.Usd);
var quantity = new Quantity(1, UnitOfMeasure.Each);
return new OrderItem(productId, quantity, price);
}
private static Mock<IOrderRepository> GetMockOrderRepository()
{
var mockRepository = new Mock<IOrderRepository>();
mockRepository.Setup(x => x.FindOrderAsync(It.IsAny<OrderId>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException(
$"This mock is set up to work with {nameof(ExistingOrderId)} and {nameof(NonExistentOrderId)}."));
mockRepository.Setup(x => x.FindOrderAsync(ExistingOrderId, It.IsAny<CancellationToken>()))
.ReturnsAsync(GetTestOrder(ExistingOrderId));
mockRepository.Setup(x => x.FindOrderAsync(NonExistentOrderId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Order?)null);
return mockRepository;
}
}
I'm trying to write a test for a service that uses IStringLocalizerFactory to translate strings. All of the translations are in a single Resource file. I cannot seem to get the Mock for it to work, as it always throws a NullReferenceException. When debugging, it shows that _localizer is null. When I remove the localizer logic completely, the test succeeds.
Code I'm trying to test:
private readonly IStringLocalizer _localizer;
public EventService(IEventRepository eventRepository, IMemberEventRepository memberEventRepository, IStringLocalizerFactory factory)
{
this._eventRepository = eventRepository;
this._memberEventRepository = memberEventRepository;
this._localizer = factory.Create(typeof(Resource));
}
public async Task CreateEventRegistrationAsync(MemberEvent entity)
{
if (await this._memberEventRepository.GetMemberEvent(entity.EventId, entity.MemberId) != null)
{
throw new ArgumentException(_localizer["This member already participates in this event."].Value);
}
await this._memberEventRepository.CreateAsync(entity);
}
My tests:
private Mock<IStringLocalizerFactory> _stringLocalizerFactoryMock = new Mock<IStringLocalizerFactory>();
public EventServiceTests()
{
_service = new EventService(_eventRepoMock.Object, _memberEventRepoMock.Object, _stringLocalizerFactoryMock.Object);
}
[Fact]
public async Task CreateEventRegistrationAsync_ShouldThrowArgumentException_WhenMemberAlreadyRegisteredForEvent()
{
int eventId = 456;
int memberId = 123;
_stringLocalizerFactoryMock.Setup(x => x.Create(typeof(Resource)))
.Returns(() => new StringLocalizer<Resource>(_stringLocalizerFactoryMock.Object));
MemberEvent registration = new MemberEvent
{
EventId = eventId,
MemberId = memberId
};
_memberEventRepoMock.Setup(x => x.GetMemberEvent(eventId, memberId))
.ReturnsAsync(registration);
await Assert.ThrowsAsync<ArgumentException>(async () => await _service.CreateEventRegistrationAsync(registration));
}
From examining the subject under test I see that
_localizer["This member already participates in this event."].Value
will throw a null exception because _localizer[...] was not setup and thus fail when .Value is invoked.
Consider mocking a IStringLocalizer<T> so that it can be setup to behave as expected when the test is invoked.
//...
var localizer = new Mock<IStringLocalizer<Resource>>();
localizer
.Setup(_ => _[It.IsAny<string>()])
.Returns(string key => new LocalizedString(key, key));
_stringLocalizerFactoryMock
.Setup(_ => _.Create(It.IsAny<Type>()))
.Returns(() => localizer.Object));
//...
I try to test this method using xunit .
public async Task<IList<DraftEntity>> Handle(GetDraftsQuery request, CancellationToken cancellationToken)
{
var res = await _repository.GetAllAsync(a => a.CustomerIsin == _user.CustomerIsin);
return res.Data;
}
Here is my test code :
public async void GetDraftsQueryTest_when_customerISIN_is_same_draft_is_not_null()
{
//Arange
IList<DraftEntity> ListOutpuddata = new List<DraftEntity>() { new DraftEntity()
{
CustomerIsin=customerisin,
}
};
repo.Setup(i => i.GetAllAsync(i=>i.CustomerIsin==It.IsAny<string>())).Returns(Task.FromResult(OperationResult<IList<DraftEntity>>.Succeed(ListOutpuddata)));
}
But when I debug the code the res variable in my method is null .Why ?
Final setup
repo.Setup(i => i.GetAllAsync(It.IsAny<Expression<Func<DraftEntity, bool>>>())).Returns(Task.FromResult(OperationResult<IList<DraftEntity>>.Succeed(ListOutpuddata)));
In my ASP.NET MVC5 web-app I'm using the EF (Model-first) for my database-communication. For unit-testing purposes, I created a generic method to generate Mock database sets. Unfortunately, I am unable to mock all the methods because when .Where(), .Any() and .Find() are used in my tested code, an exception is thrown. Can anyone help me on this? My code is below.
Unittest:
[TestClass()]
public class MessagingServiceTests
{
Mock<BoatstersEntitiesContainer> _mockContext;
MessagingService _service;
string _connectionId;
Guid _userId;
[TestInitialize()]
public void TestInitialize()
{
_userId = Guid.Parse("12345678-1234-1234-1234-123412344142");
_connectionId = "abc123";
// Setup entities
User user = new User { Id = _userId, CustomerId = 1 };
Customer customer = new Customer { Id = 1, User = user, FirstName = "TestFirstName" };
user.Customer = customer;
Customer boatOwnerCustomer = new Customer { Id = 2, FirstName = "BoatOwner" };
Boat boat = new Boat { Id = 1, Customer = boatOwnerCustomer, CustomerId = boatOwnerCustomer.Id };
boatOwnerCustomer.Boats.Add(boat);
// Init mocksets
var userMockSet = MockDbSet.Build(new List<User> { user });
var customerMockSet = MockDbSet.Build(new List<Customer> { customer, boatOwnerCustomer });
var conversationMockSet = MockDbSet.Build(new List<Conversation>());
var messageMockSet = MockDbSet.Build(new List<Message>());
var boatMockSet = MockDbSet.Build(new List<Boat> { boat });
var messagingHubConnectionMockSet = MockDbSet.Build(new List<MessagingHubConnection>());
// Setup mockcontext
_mockContext = new Mock<BoatstersEntitiesContainer>();
_mockContext.Setup(m => m.Users).Returns(userMockSet.Object);
_mockContext.Setup(m => m.Customers).Returns(customerMockSet.Object);
_mockContext.Setup(m => m.Conversations).Returns(conversationMockSet.Object);
_mockContext.Setup(m => m.Messages).Returns(messageMockSet.Object);
_mockContext.Setup(m => m.Boats).Returns(boatMockSet.Object);
_mockContext.Setup(m => m.MessagingHubConnections).Returns(messagingHubConnectionMockSet.Object);
// Start service
_service = new MessagingService(_mockContext.Object, _userId);
}
[TestMethod()]
public void When_PartnerConnected_IsTrue()
{
Conversation conversation = new Conversation {
Id = 1,
Boat = _mockContext.Object.Boats.First(b => b.Id.Equals(1)),
BoatId = _mockContext.Object.Boats.First(b => b.Id.Equals(1)).Id
};
conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(1)));
conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(2)));
MessagingHubConnection connection = new MessagingHubConnection
{
Id = 1,
Connected = true,
ConnectionId = "abc123",
Conversation = conversation,
ConversationId = 1,
Customer = _mockContext.Object.Customers.First(b => b.Id.Equals(2)),
CustomerId = 2
};
conversation.MessagingHubConnections.Add(connection);
_mockContext.Object.MessagingHubConnections.Add(connection);
_mockContext.Object.Conversations.Add(conversation);
var result = _service.IsPartnerConnected();
Assert.IsTrue(result);
// Clean up
_mockContext.Object.Conversations.RemoveRange(_mockContext.Object.Conversations);
_mockContext.Object.MessagingHubConnections.RemoveRange(_mockContext.Object.MessagingHubConnections);
}
}
Generic mockset creator:
public static class MockDbSet
{
public static Mock<DbSet<TEntity>> Build<TEntity>(List<TEntity> data) where TEntity : class
{
var queryable = data.AsQueryable();
var mockSet = new Mock<DbSet<TEntity>>();
mockSet.As<IQueryable<TEntity>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockSet.As<IQueryable<TEntity>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockSet.As<IQueryable<TEntity>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
mockSet.Setup(m => m.Add(It.IsAny<TEntity>())).Callback<TEntity>(data.Add);
return mockSet;
}
}
Messagingservice (which is being tested)
public class MessagingService : BaseRepository<Conversation>
{
private readonly Customer _customer;
private MessagingHubConnection _connection;
public MessagingService(BoatstersEntitiesContainer context, Guid userId) : base(context)
{
Context = context;
_customer = Context.Customers.First(c => c.User.Id == userId);
}
public bool IsPartnerConnected()
{
// Check if partner is connected
return Context.MessagingHubConnections.Any(c => c.ConversationId.Equals(_connection.ConversationId) && c.Customer.Id != _customer.Id && c.Connected);
}
}
In MessagingService.IsPartnerConnected(), the following exception is thrown:
Test Name: When_PartnerConnected_IsTrue
Test FullName: Boatsters.Sunshine.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue
Test Source: C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Sunshine.UnitTests\MessagingServiceUnitTest.cs : line 94
Test Outcome: Failed
Test Duration: 0:00:00,0289022
Result StackTrace:
bij lambda_method(Closure , MessagingHubConnection )
bij System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)
bij lambda_method(Closure )
bij System.Linq.EnumerableExecutor1.Execute()
bij System.Linq.EnumerableQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
bij System.Linq.Queryable.Any[TSource](IQueryable1 source, Expression1 predicate)
bij Boatsters.Services.MessagingService.IsPartnerConnected() in C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Services\MessagingService.cs:line 156
bij xxx.MessagingServiceTests.When_PartnerConnected_IsTrue() in C:\xxx\MessagingServiceUnitTest.cs:line 118
Result Message:
Test method
xxx.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue threw exception:
System.NullReferenceException: Object reference not set to an instance of an object
Based on review of MessagingService, it is not immediately apparent where _connection is assigned a value. Looks like that is what is null when the method under test is called based on stack trace lambda_method(Closure , MessagingHubConnection )
Also from past experiences with Moq and DbSet<>, this line needs to updated so that multiple calls can be made to the data source.
mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
Change the .Returns(queryable.GetEnumerator()) to return a Func
mockSet.As<IQueryable<TEntity>>()
.Setup(m => m.GetEnumerator())
.Returns(() => queryable.GetEnumerator()); //<-- Note change here.
The original will return the same enumerator for every call which can only be enumerated once and may cause issues. Using the Func will allow a fresh enumerator to be return on every call to allow for multiple passes on the data source.
I have the following method:
public async Task<string> GetDescription(int codeId)
{
var Codes = Context.Codes.Where(x => x.Id == codeId).FirstOrDefault();
return Codes.Description;
}
and the following unit test:
[Test]
public async Task GetDescription()
{
var result = await _serivce.GetSpecialtyDescription(1);
Assert.That(result == "description");
}
and I setup my test like this:
public ServicesTests()
{
_dbContext = new Mock<LocalContext>();
var CodeList = new List<Codes>() { new Codes() { Id = 1, Description = "description" } };
var dbSetCodeList = MockDbSet.GetQueryableMockDbSet(CodeList);
_dbContext.Setup(x => x.Codes).Returns(dbSetCodeList.Object);
_context = new DataContext<LocalContext, LocalContext>(_dbContext.Object);
_serivce = new CodesServices(_context);
}
public static Mock<DbSet<T>> GetQueryableMockDbSet<T>(List<T> sourceList) where T : class
{
var queryable = sourceList.AsQueryable();
var dbSet = new Mock<DbSet<T>>();
dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s));
return dbSet;
}
Which all works fine.
Now, I want to await the function, so do this:
public async Task<string> GetDescription(int codeId)
{
var Codes = await Context.Codes.Where(x => x.Id == codeId).FirstOrDefaultAsync();
return Codes.Description;
}
but this breaks my unit test - even though the code still works.
I have read plenty of articles and posts explaining that this does not work as the async methods cannot be mocked (I think?), but I have not come across anything which shows me how to resolve this.
I would be disappointing if I was forced to choose between awaiting my code or having a unit test, and feel sure there must be a way around this?
I am not happy with the result, but this is the best I can do so far:
public async Task<string> GetDescription(int codeId)
{
var Codes = await GetAll();
return Codes.Description;
}
private async Task<DbSet<Codes>> GetAll()
{
return Context.Codes;
}
If anyone has a better suggestion please let me know.