1

In my test method, I want to test context.T.AddAsync method and Its output. Below is the code for the method.

var addRequest = await _context.AddAsync<Request>(requestEntity, cancellationToken);
if (addRequest.State == Microsoft.EntityFrameworkCore.EntityState.Added)
{
    Console.WriteLine("Added: " + user.Requests.Count);
    saveChanges = await _context.SaveChangesAsync(cancellationToken);
}
else
{
    //handle failed AddAsync of the requestEntity
}

Since the result of AddAsync method is being used after that, I have to define a response for that in my test method. Type of addRequest is

Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Request>

For that, I use A.CallTo, and below is the test method

A.CallTo(() => _request.AddAsync(A<Request>.Ignored, new CancellationToken())).Returns(_addAsyncResponse); 

The problem is, I can't figure out how to create the _addAsyncResponse object. I tried with

_addAsyncResponse = new EntityEntry<Request>() { };

and it's not working.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ayesh Nipun
  • 568
  • 12
  • 28

1 Answers1

0

So, after 2 days of researching, I was able to complete this with an in-memory database.

steps

  1. Create an in-memory database.
  2. Call the actual AddAsync method with a Request object.
  3. Assign the result of AddAsync to a var
  4. In the above A.CallTo method, add the above-defined var in the Returns method.

Sample code -

var options = new DbContextOptionsBuilder<DataContext>()
   .UseInMemoryDatabase(databaseName: "FakeDB")
   .Options;
    
var context = new DataContext(options);
var addAsyncResult = context.Requests.AddAsync(new Request());
    
               
A.CallTo(() => _context.Requests).Returns(_request);
A.CallTo(() => _context.AddAsync(A<Request>.Ignored, new CancellationToken())).Returns(addAsyncResult);
A.CallTo(() => _context.SaveChangesAsync(new CancellationToken())).Returns(1);
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ayesh Nipun
  • 568
  • 12
  • 28