Van*_*nel 9 c# nunit unit-testing asp.net-core
我正在使用C#和.NET Core 2.0开发ASP.NET Core 2 web api.
我已经更改了一个方法来添加try-catch以允许我返回状态代码.
public IEnumerable<GS1AIPresentation> Get()
{
return _context
.GS1AI
.Select(g => _mapper.CreatePresentation(g))
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
变成:
public IActionResult Get()
{
try
{
return Ok(_context
.GS1AI
.Select(g => _mapper.CreatePresentation(g))
.ToList());
}
catch (Exception)
{
return StatusCode(500);
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我的Test方法有问题,因为现在它返回的是一个IActionResult而不是IEnumerable<GS1AIPresentation>:
[Test]
public void ShouldReturnGS1Available()
{
// Arrange
MockGS1(mockContext, gs1Data);
GS1AIController controller =
new GS1AIController(mockContext.Object, mockMapper.Object);
// Act
IEnumerable<Models.GS1AIPresentation> presentations = controller.Get();
// Arrange
Assert.AreEqual(presentations.Select(g => g.Id).Intersect(gs1Data.Select(d => d.Id)).Count(),
presentations.Count());
}
Run Code Online (Sandbox Code Playgroud)
我的问题在这里:IEnumerable<Models.GS1AIPresentation> presentations = controller.Get();.
我是否需要重构一个新的方法来测试Select?
这个选择:
return _context
.GS1AI
.Select(g => _mapper.CreatePresentation(g))
.ToList();
Run Code Online (Sandbox Code Playgroud)
或者,也许我能得到IEnumerable<Models.GS1AIPresentation>的IActionResult
在return Ok(...)所谓的控制器返回一个OkObjectResult,它来源于IActionResult所以你需要投那个类型,然后访问中的值.
[Test]
public void ShouldReturnGS1Available() {
// Arrange
MockGS1(mockContext, gs1Data);
var controller = new GS1AIController(mockContext.Object, mockMapper.Object);
// Act
IActionResult result = controller.Get();
// Assert
var okObjectResult = result as OkObjectResult;
Assert.IsNotNull(okObjectResult);
var presentations = okObjectResult.Value as IEnumerable<Models.GS1AIPresentation>;
Assert.IsNotNull(presentations);
Assert.AreEqual(presentations.Select(g => g.Id).Intersect(gs1Data.Select(d => d.Id)).Count(),
presentations.Count());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4606 次 |
| 最近记录: |