如何单元测试 API 控制器方法

How to UNit test the API controller methods

我真的很困,需要你的帮助。

我有一个 .NET Core 2.1 API,我想创建一个 nUnitTest 项目 (NUnit 3.10.1) 来测试 API 的控制器,但是 我没有不知道如何从 nUnitTest 调用控制器的操作方法,确实需要一些帮助

我尝试过的事情:

1) 在控制器中生成无参数构造函数并从 Test 方法实例化控制器,但这不起作用。

2) 在测试中生成一个构造函数 class 来定义数据库上下文,但这也不起作用。

这是我的 API 控制器:

public class PersonController : ControllerBase
{
    private readonly NetCoreAPI1Context _context;

    public PersonController(NetCoreAPI1Context context)
    {
        _context = context;
    }

    // POST: api/Person
    [HttpPost]
    public async Task<IActionResult> PostPerson([FromBody] Person person)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Persons.Add(person);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetPerson", new { id = person.Id }, person);
    }
}

这里是NetCoreAPI1Contextclass

public class NetCoreAPI1Context : DbContext
{
    public NetCoreAPI1Context(DbContextOptions<NetCoreAPI1Context> options)
      : base(options)
    {
    }
    public DbSet<Person> Persons { get; set; }
}

这里是Personclass

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

我已验证控制器中的 PostPerson 操作有效。

然后我将一个 nUnitTest 项目添加到解决方案中。

这是我的简单测试class和方法:

class PersonControllerTest
{
    Person _person;

    //NetCoreAPI1Context _context;

    [SetUp]
    public void Setup()
    {
        _person = new Person
        {
            FirstName = "David",
            LastName = "Johnson",
            Email = "dj@dj.com"
        };
    }

    //public PersonControllerTest(NetCoreAPI1Context context)
    //{
    //    _context = context;
    //}

    [Test]
    public void PostPersonTest()
    {
        var person = _person; // confirm that "person" has data and ready to be used
        //
        // HOW To CALL THE COTROLLER METHOD PostPerson(...) HERE????
        //

    }
}

这里是关于如何进行 NUnit 测试的步骤:

1.In你的nUnitTest项目,你需要右击Dependences并选择add reference(Web Api project): 2.WebApi 项目负责人:

[Route("api/[controller]")]
[ApiController]
public class PeopleController : ControllerBase
{
    private readonly WebApi2Context _context;

    public PeopleController(WebApi2Context context)
    {
        _context = context;
    }

    // GET: api/People
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Person>>> GetPerson()
    {
        return await _context.Person.ToListAsync();
    }
    // POST: api/People
    [HttpPost]
    public async Task<ActionResult> PostPerson(Person person)
    {
        _context.Person.Add(person);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetPerson", new { id = person.Id }, person);
    }
}

3.nUnitTest 项目(确保您已经安装了软件包 Microsoft.EntityFrameworkCoreMicrosoft.EntityFrameworkCore.SqlServer):

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using WebApi2.Controllers;
using WebApi2.Data;
using WebApi2.Models;
namespace NUnitTestProject1
{
    class PersonControllerTest
    {
        public static DbContextOptions<WebApi2Context> dbContextOptions { get; }
        public static string connectionString = "Server=(localdb)\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true";
        Person _person;
        static PersonControllerTest()
        {
            dbContextOptions = new DbContextOptionsBuilder<WebApi2Context>()
                .UseSqlServer(connectionString)
                .Options;
        }
        [SetUp]
        public void Setup()
        {
            _person = new Person
            {
                //Id=1,If Id is not designed by using IDENTITY (1, 1),you need to add this line
                FirstName = "David",
                LastName = "Johnson",
                Email = "dj@dj.com"
            };
        }
        [Test]
        public void Test1()
        {
            var context = new WebApi2Context(dbContextOptions);
            PeopleController person = new PeopleController(context);
            var data = person.PostPerson(_person);
            var response = data.Result as CreatedAtActionResult;
            var item = response.Value as Person;
            Assert.AreEqual("David", item.FirstName);
            Assert.AreEqual("Johnson", item.LastName);
            Assert.AreEqual("dj@dj.com", item.Email);

        }
    }
}

4.Result: