似乎当一个异常在一个事件引发中被引发时,它会被Moq捕获,而不会被检测到。可能是因为它是异步的?(在任务中被捕获。异常)。
范例:
internal class Program
{
static async Task Main(string[] args)
{
var eventManager = new EventManager();
var eventConsumer = new EventConsumer(eventManager);
await eventManager.OnEventHappened(1000);
Console.WriteLine("Unreacheble, exception thrown");
}
}
public delegate Task CustomEvent(int number);
public interface IEventManager
{
event CustomEvent CustomEvent;
}
public class EventConsumer
{
private readonly IEventManager _eventManager;
public EventConsumer(IEventManager eventManager)
{
_eventManager = eventManager;
_eventManager.CustomEvent += _eventManager_CustomEvent;
}
private async Task _eventManager_CustomEvent(int number)
{
await Task.Delay(number);
throw new NotImplementedException();
}
}
public class EventManager : IEventManager
{
public event CustomEvent CustomEvent;
public async Task OnEventHappened(int number)
{
await CustomEvent.Invoke(number);
}
}
字符串
例如,这些测试失败(预期异常,但为空)。
[Test]
public void ShouldThrowException()
{
var eventManagerMock = new Mock<IEventManager>(MockBehavior.Strict);
var consumer = new EventConsumer(eventManagerMock.Object);
Assert.Throws<NotImplementedException>(() => eventManagerMock.Raise(x => x.CustomEvent += null, 1000));
}
[Test]
public void ShouldThrowException2()
{
var eventManagerMock = new Mock<IEventManager>(MockBehavior.Strict);
var consumer = new EventConsumer(eventManagerMock.Object);
eventManagerMock.Setup(x => x.OnEventHappened(1000)).Returns(Task.CompletedTask).Raises(x => x.CustomEvent += null, 1000);
Assert.ThrowsAsync<NotImplementedException>(() => eventManagerMock.Object.OnEventHappened(1000));
}
型
是我做错了什么,还是它真的是一个错误?
I have opened an issue on moq's repro,但到目前为止还没有得到任何回应。
谢谢你,谢谢
1条答案
按热度按时间0ve6wy6x1#
这似乎是一个可以通过RaiseAsync方法解决的问题,但是在撰写本文时,它还没有发布。
我会更新这个答案,一旦它被释放,并确认解决问题。
https://github.com/moq/moq/blob/main/CHANGELOG.md