【发布时间】:2023-03-28 14:36:02
【问题描述】:
我有这样的系统
class Sut
{
IRepository _repo;
public Sut(IRepository repo) { _repo = repo; }
async Task Handle(Request request)
{
var entity = new Entity(request.Id); //=> if Id is not ok the Entity throws Exception
_repo.Save(entity);
}
}
这是测试
[Fact]
public async Task Test_Save()
{
Mock<IRepository> repositoryMock = new Mock<IRepository>();
repositoryMock
.Setup(repo => repo.Save(It.IsAny<Entity>()))
.Returns(Task.CompletedTask);
var sut = new Sut(repositoryMock.Object);
/// Act
Action action = async () => await sut.Handle(new Request { Id = default(Guid)});
/// Assert
Assert.Throws<Exception>(action);
repositoryMock.Verify(repo => repo.Save(It.IsAny<Entity>(), Times.Never);
}
所以它的作用是,Entity 对传递给它的默认Guid 进行检查。如果传递默认值,则会抛出异常。
抛出异常,但测试失败并显示此消息。
消息:Assert.Throws()
预期失败:typeof(System.Exception)
实际:(没有抛出异常)
测试从不调用
repositoryMock.Verify(repo => repo.Save(It.IsAny<Entity>(), Times.Never);
它将在这一行中断
为什么会这样以及如何解决这种情况?
Assert.Throws<Exception>(action);
更新
public Entity(Guid id)
{
if (default(Guid) == id) throw new Exception("cannot have a default value for id");
Id = id;
}
【问题讨论】:
-
你在控制
Entity吗? -
显示
Entity,因为它与语句if Id is not ok the Entity throws Exception有关 -
好的,我想我看到了问题所在。
Action action基本上是async void,这意味着抛出的异常不会被捕获。 -
我也尝试过不使用 Action 并删除 Assertion 部分,只留下 Verification,当我这样做时,我得到异常 Message: Sytem.Exception : cannot have a default value for id
标签: c# unit-testing testing moq