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)));
Related
We have some external service method to call from our code, looks. like
AssignOrderReserveCommandResponseDto response = await _supplyReservesClient.AssignOrderReserve(
masterReserveId,
inboundReserveId,
deliveryDate,
orderInfos,
cancellationToken)
Mock for this method looks like:
public static readonly ISupplyReservesClient SupplyReservesClient = Substitute.For<ISupplyReservesClient>();
public static AssignOrderReserveCommandResponseDto assignOrderReserveCommandResponse;
static SupplyReservesClientMock()
{
SupplyReservesClient
.AssignOrderReserve(Arg.Any<Guid>(), Arg.Any<Guid>(),
Arg.Any<DateTimeOffset>(), Arg.Any<IReadOnlyCollection<AssignOrderInfo>>(),
Arg.Any<CancellationToken>())
.Returns(_ => assignOrderReserveCommandResponse);
}
public static void SetAssignOrderReserveCommandResponseDto(long bidId, long otherBidId)
{
Fixture fixture = new Fixture();
assignOrderReserveCommandResponse = fixture.Build<AssignOrderReserveCommandResponseDto>()
.With(x => x.OrderInfos, new List<AssignOrderReserveCommandResponseDto.OrderInfo>()
{
new(bidId, "1", DateTime.UtcNow.AddDays(3)),
new(otherBidId, "1", DateTime.UtcNow.AddDays(3))
})
.With(x => x.InboundReserveId, fixture.Create<Guid>())
.Create();
}
Mock doesn't work and method returns null when I use debug for my test or just run test
Method for mock:
public async Task<AssignOrderReserveCommandResponseDto> AssignOrderReserve(
Guid? masterReserveId,
Guid? inboundReserveId,
DateTimeOffset deliveryDate,
IReadOnlyCollection<AssignOrderInfo> orderInfos,
CancellationToken cancellationToken)
{
AssignOrderReserveCommand command = AssignOrderReserveConverter
.Convert(masterReserveId, inboundReserveId, deliveryDate, orderInfos);
AssignOrderReserveCommandResponse response = await _supplyReservesClient
.AssignOrderReserveAsync(command, cancellationToken: cancellationToken);
return AssignOrderReserveConverter.Convert(response);
}
I created a azure function with the time trigger code below. Im very new to azure function and xunit. I created both with help of some blogs. I wrote a simple unit test using Xunit in C#. but it returns an error. I tried to solve the issue and not work for me.. Please help me
public class DeleteJob
{
private readonly IStore _store;
public DeleteJob(IStore store, ILogger<DeleteJob> log)
{
_store = store;
_log = log;
}
[Function("DeleteJob")]
public async Task Run([TimerTrigger("0 */5 * * * *", RunOnStartup = false)] MyInfo myTimer)
{
var canceltoken = new CancellationTokenSource(TimeSpan.FromMinutes(8));
var deleteDate = DateTime.UtcNow.AddMonths(-6);
try
{
await DeleteBlobMetadata(deleteDate, canceltoken.Token);
}
catch (OperationCanceledException)
{
_log.LogInformation("Function ran out of time");
}
}
private async Task DeleteBlobMetadata(DateTime deleteDate, CancellationToken canceltoken)
{
try
{
if (cancellationToken.IsCancellationRequested)
return;
var BlobUrls = await _store.GetBlobBeforeDate(Constants.ContainerName, deleteDate);
foreach (var blobName in BlobUrls)
{
if (cancellationToken.IsCancellationRequested)
return;
await _store.DeleteBlobAsync(Constants.ContainerName, blobName);
}
}
catch (Exception e)
{
_log.LogError($"Exception when deleting attachments: \n{e}");
}
Following is unittest
public class DeleteTest
{
private readonly Mock<IStore> _StoreMock;
private Mock<ILogger<DeleteJob>> _logMock;
public DeleteTest()
{
_StoreMock = new Mock<IStore>();
_logMock = new Mock<ILogger<DeleteJob>>();
}
[Fact]
public async Task DeleteBlobOlderThan6Months_ShouldDelete()
{
SetupDeletionSuccessful(true);
SetupDeleteBlobSetup();
var sut = GetSut();
await sut.Run(myTimer: null);
_StoreMock.Verify(m => m.GetBlobBeforeDate(It.IsAny<string>(),It.IsAny<DateTime>()), Times.Exactly(1));
_StoreMock.Verify(m => m.DeleteAttachmentAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(1));
}
private void SetupDeleteBlobSetup()
{
_StoreMock.Setup(m => m.GetBlobBeforeDate(It.IsAny<string>(),It.IsAny<DateTime>()))
.ReturnsAsync(new List<string> { "someUrl" });
}
private void SetupDeletionSuccessful(bool successfulDeletion)
{
_StoreMock.Setup(m => m.DeleteAttachmentAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(successfulDeletion);
}
Error is
Expected invocation on the mock exactly 1 times, but was 0 times:
m => m.GetBlobBeforeDate(It.IsAny<string>(), It.IsAny<DateTime>())
The error message is perfectly right. In your test the GetBlobBeforeDate() does not get called:
In your test setup the GetBlobBeforeDate method to return an empty list:
_StoreMock.Setup(m => m.GetBlobBeforeDate(It.IsAny<string>(),It.IsAny<DateTime>()))
.ReturnsAsync(new List<string>());
This means in you function there will be no blob url to delete. Because in your function you delete all blobUrls that have been returned by GetBlobBeforeDate. No items => nothing to delete.
If you want your test to verify that DeleteAttachmentAsync gets called exactly once you need a new setup. For example:
_StoreMock.Setup(m => m.GetBlobBeforeDate(It.IsAny<string>(),It.IsAny<DateTime>()))
.ReturnsAsync(new List<string> { "someUrl" });
Edit:
On more thing, this time in your code you call:
await _store.DeleteBlobAsync(Constants.AttachmentContainerName, blobName);
But what should be the corresponding Mock setup is:
_StoreMock.Setup(m => m.DeleteAttachmentAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(successfulDeletion);
As you can see you are comparing apples to oranges. The error is still right: DeleteAttachmentsAsync never gets called.
Also in your code you use both Constants.ContainerName nad Constants.AttachmentContainerName which also seems wrong.
I suggest to setup your Mocks a little bit more explicit and include the corresponding container name. For example:
_StoreMock.Setup(m => m.GetBlobBeforeDate(Constants.ContainerName, It.IsAny<DateTime>()))
.ReturnsAsync(new List<string> { "someUrl" });
This way the mock will also verify that the method has been called with the expected containerName parameter value.
everyone.
I have been trying write mock test to my IElasticClient calls, but I have problem with a error about convert. Convert IGetResponse to GetResponse.
My method of ElasicClient:
public class GetClientByIdQueryHandler : IQueryHandler<GetClientByIdQuery, Client>
{
private readonly IElasticClient _elasticClient;
private readonly IReadModel _readModel;
public GetProposalByIdQueryHandler(IElasticClient elasticClient, IReadModel readModel)
{
...
}
public async Task<Client> ExecuteQueryAsync(GetClientByIdQuery query, CancellationToken cancellationToken)
{
var readModelDescription = _readModel.GetReadModelDescription<ClientReadModel>();
var indexName = readModelDescription.IndexName.Value;
var getResponse = await _elasticClient
.GetAsync<ClientReadModel>(query.Id.Value, d => d.Index(indexName).RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)), cancellationToken)
.ConfigureAwait(false);
return getResponse.Source;
}
}
My Mock test:
private const string _indexName = "client-document";
private ClientReadModel GetClientReadModel()
{
var response = JsonConvert.DeserializeObject<ClientReadModel>("...string json...");
return response;
}
[Fact]
public async Task GetClientByIdQueryHandler()
{
// Arrange
var mockElasticClient = new Mock<IElasticClient>();
var mockResponse = new Mock<IGetResponse<ClientReadModel>>();
mockResponse.SetupGet(r => r.Source).Returns(GetClientReadModel());
mockElasticClient
.Setup(x => x.GetAsync(
"id-d862975d-06ea-4f50-b7d3-d2b19413cb4c",
It.IsAny<Func<GetDescriptor<ClientReadModel>, IGetRequest>>(),
It.IsAny<CancellationToken>()))
.Returns(mockResponse.Object); // <== error here
...
...
}
Almost alright, but it returns a error on the line "Returns(mockResponse.Object);":
cannot convert from 'Nest.IGetResponse' to 'Nest.GetResponse
Someone have idea about resolve this problem?
Thanks!
I have a test method that is failing on sso.verify notice the CheckUsername method has two await calls in a async method ? but because of that the sso verify never returns and thus is not verified. But the code is called. What would be the proper way to test this ?
public void Setup()
{
nav = new Mock<INavService>();
sso = new Mock<ISSOApiService>();
_vm_Successs = new ForgotPasswordViewModel(nav.Object, sso.Object);
sso.Setup(x => x.SendEmailCodeRequestAsync(It.IsAny<PasswordTokenRequest>())).ReturnsAsync(new StandardResponse() { ErrorCode = null }).Verifiable();
nav.Setup(x => x.NavigateTo<ForgotPasswordEnterCodeModel, string>(It.IsAny<string>())).Verifiable();
}
[Test]
public void CheckUserName_Success()
{
_vm_Successs.UserName = "Timmy";
var response = _vm_Successs.CheckUsername();
sso.Verify(e => e.SendEmailCodeRequest(It.IsAny<PasswordTokenRequest>()), Times.Once);
nav.Verify(mock => mock.NavigateTo<ForgotPasswordEnterCodeModel, string>(It.IsAny<string>()), Times.Once);
}
This is the checkusername method
public async Task CheckUsername()
{
PasswordTokenRequest r = new PasswordTokenRequest();
await SSOAPIService.SendEmailCodeRequestAsync(r);
await NavService.NavigateTo<ForgotPasswordEnterCodeModel, string>(UserName);
}
you should await test method therefore you need to make your test 'async Task' type
also need to setup SendEmailCodeRequestAsync with ReturnsAsync
[Test]
public async Task ShouldDeleteAzureBlobById()
{
sso.Setup(x => x.SendEmailCodeRequestAsync(It.IsAny<PasswordTokenRequest>()))
.ReturnsAsync(new StandardResponse() { ErrorCode = null })
.Verifiable();
_vm_Successs.UserName = "Timmy";
var response = await _vm_Successs.CheckUsername();
sso.Verify(e => e.SendEmailCodeRequestAsync(It.IsAny<PasswordTokenRequest>()), Times.Once);
nav.Verify(mock => mock.NavigateTo<ForgotPasswordEnterCodeModel, string>(It.IsAny<string>()), Times.Once);
}
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?