0

this test always return null, and test always fail...but when i run the projet all works fine and return data normally, this project using RavenDB

Controller

[Route("api/[controller]")]
public class CategoryController : Controller
{
    private readonly AppDbContext _context = new AppDbContext();

    // GET: api/category
    [HttpGet("{id}")]
    public async Task<JsonResult> Get(string id)
    {
        using (IAsyncDocumentSession session = _context.SessionAsync){
            var result = await session.LoadAsync<Category>(id);
            return Json(result);
        }
    }
} 

and using xUnit to testing

 [Fact]
public async Task GetShouldReturnCategory()
{
    // Arrange
    var _categoryController = Substitute.For<CategoryController>();
    var category = CreateCategory();

    // Act
    var result = await _categoryController.Get(category.Result.Id);

    //Asserts here
}

1 Answer 1

2

Base on your question, system under test (SUT) is CategoryController. So, it doesn't make sense to mock CategoryController; instead, you want to mock AppDbContext.

If you want to unit test a controller, you should use ASP.NET Core's Dependency Inject, and inject its dependencies via constructor injection. In other words, you should not use new.

Normally, we inject interface instead of concrete class, so that we can easily mock it.

Your code is missing too many pieces, so I could only give you a directly. You want more detail you can look at this sample project at GitHub which uses NSubstitute and XUnit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.