Charlie Hal
Charlie Hal

Reputation: 29

ASP.NET Core Test xUnit Controller

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
}

Upvotes: 0

Views: 436

Answers (1)

Win
Win

Reputation: 62300

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.

Upvotes: 2

Related Questions