无法使用 xunit 测试检查 returnType 是否为 HttpNotFoundResult mvc.controller
Trouble checking if the returnType is HttpNotFoundResult using xunit testing mvc.controller
我正在尝试测试 Microsoft.AspNet.Mvc.Controller
return Task<IActionResult>
如果传入的 id 被命中,return 是 HttpNotFound()
如果没有点击率。
我如何使用 xUnit 测试我返回的是 HttpNotFound 还是实际结果?
这是控制器方法:
[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);
我正在尝试测试 Microsoft.AspNet.Mvc.Controller
return Task<IActionResult>
如果传入的 id 被命中,return 是 HttpNotFound()
如果没有点击率。
我如何使用 xUnit 测试我返回的是 HttpNotFound 还是实际结果?
这是控制器方法:
[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);