【发布时间】:2017-04-21 09:58:43
【问题描述】:
框架
.NETCoreApp 1.1
EF Core 1.1.1
Xunit 2.2.0
Moq 4.7.8
Controller Post 方法_yourRepository 被注入到控制器构造函数中,其类型为 IYourRepository
[HttpPost(Name = "CreateMethod")]
public async Task<IActionResult> CreateMethod([FromBody] ObjectForCreationDto objectDto)
{
if (objectDto== null)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest();
}
await _yourRespository.CreateObject(objectDto);
if (!await _yourRespository.Save())
{
throw new Exception("Creating this object failed on save.");
}
return Ok();
}
单元测试失败
[Fact]
public async Task CreateObject_WhenGoodDtoReceived_SuccessStatusReturned()
{
// Arrange
var mockRepo = new Mock<IYourRepository>();
var controller = new YourController(mockRepo.Object);
var objectForCreationDto = new ObjectForCreationDto { Code = "0001", Name = "Object One" };
// Act
var result = await controller.CreateObject(objectForCreationDto);
// Assert
Assert.IsType<OkObjectResult>(result);
}
测试失败是因为这条线
if (!await _yourRespository.Save())
总是评估为真。当它评估为 true 时,您可以看到代码抛出错误(由中间件处理)
_yourRepository.Save() 方法
public async Task<bool> Save()
{
return (await _yourContext.SaveChangesAsync() >= 0);
}
我不确定如何解决问题,也不是 100% 确定它为什么会失败。
是因为模拟的IYourRepository 接口不包含Save 方法的实现吗?
如果是这样,这是否意味着要测试 Post 方法,我需要模拟我的 DbContext 并使用它构造我的 YourRepository 对象?
任何关于为什么失败以及如何纠正它的解释将不胜感激
【问题讨论】:
-
代替
await _yourRespository.Save()试试_yourRespository.Save().Wait() -
他正在使用模拟,_yourRepository 没有功能。这就是模拟的全部意义,不是有一个具体的实现,而是“伪造”你希望它返回的结果
标签: c# asp.net-core moq entity-framework-core xunit2