Skip to main content
 首页 » 编程设计

c#之无法使用 xunit 测试 mvc.controller 检查 returnType 是否为 HttpNotFoundResult

2024年02月05日13findumars

我正在尝试测试 Microsoft.AspNet.Mvc.Controller返回 Task<IActionResult>如果传入的 id 被命中,并返回 HttpNotFound()如果没有命中。

我如何使用 xUnit 测试我返回的是 HttpNotFound 还是实际结果?

这是 Controller 方法:

[HttpGet("{id}")] 
public async Task<IActionResult> Get(string id) 
{ 
    var company = await _repository.GetSingle(id); 
    if (company == null) 
        return HttpNotFound(); 
 
    return new ObjectResult(company); 
} 

这是测试方法(不起作用):

[Theory] 
[InlineData("1")] 
[InlineData("01")] 
[InlineData("10")] 
public async void TestGetSingleNonExistingCompany(string id) 
{ 
    var controller = new CompanyController(new CompanyRepositoryMock()); 
    try 
    { 
        var res = await controller.Get(id); 
        Assert.False(true); 
    } 
    catch (Exception e) 
    { 
        Assert.True(true); 
    } 
} 

我猜问题是 controller.Get(id)实际上并没有抛出 Exception , 但我不能使用 typeOf , 因为 res 的类型变量是在编译时决定的,而不是运行时。

运行 Assert.IsType 时:

[Theory] 
[InlineData("1")] 
[InlineData("01")] 
[InlineData("10")] 
public async void TestGetSingleNonExistingCompany(string id) 
{ 
    var controller = new CompanyController(new CompanyRepositoryMock()); 
    var res = await controller.Get(id); 
    Assert.IsType(typeof (HttpNotFoundResult), res.GetType()); 
} 

我收到这条消息:

Assert.IsType() Failure 
Expected: Microsoft.AspNet.Mvc.HttpNotFoundResult 
Actual:   System.RuntimeType 

有什么想法吗?

请您参考如下方法:

Assert.IsType的第二个参数应该是您正在检查其类型而不是对象类型的对象本身。试试这个,当返回 HttpNotFound() 的结果时,您的断言应该成功:

Assert.IsType(typeof (HttpNotFoundResult), res);