控制器:
private IBeer _beerService;
public BeerController(IBeer beerService)
{
_beerService = beerService;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Beer model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var beer = await _beerService.Add(model);
return Ok(CreatedAtAction("Add Item", new { beer.id }, beer));
}
型号:
public class Beer
{
public int id { get; set; }
public string name { get; set; }
public int cost { get; set; }
}
接口:
public interface IBeer
{
Task<Beer> Add(Beer beer);
}
测试:
[Fact]
public void TestPostWithMock()
{
// Arrange
var serviceMock = new Mock<IBeer>();
List<Beer> expected = new List<Beer>()
{
new Beer{id=2, beer="Kingfisher", cost=170 },
};
serviceMock.Setup(x => x.Add(expected)).Returns(() => Task.FromResult(beer));
var controller = new BeerController(serviceMock.Object);
// Act
var result = controller.Get(2);
// Assert
var okResult = result.Should().BeOfType<OkObjectResult>().Subject;
var actual = okResult.Value.Should().BeAssignableTo<IEnumerable<Beer>>().Subject;
Assert.Equal(expected, actual);
}
我正在尝试模拟发帖请求,但是当我在此处尝试模拟发帖请求时:
x => x.Add(expected)
这给我一个错误-Generic.list无法转换为Controller.Beer。应该怎么做?
答案 0 :(得分:1)
正如错误描述所述,您在设置服务时将啤酒清单(List<Beer>
)发送到Add()
方法。您应该发送Beer
类实例(如在您的界面中)作为参数,如下所示。
// Update your request object without List
var expected = new Beer()
{
id=2,
beer="Kingfisher",
cost=170
};
而且,如下更新安装程序功能。
serviceMock.Setup(x => x.Add(expected)).Returns(() => Task.FromResult(expected));
最后,您需要像控制器一样从controller.Post()
方法获得结果,而不是从controller.Get(2)
获得结果。希望对您有帮助。