我有一个接口(interface),它在另一个接口(interface)上有一个属性,
public interface IInnerInterface
{
event EventHandler OnCompleted;
}
public class InnerClassImplementation : IInnerInterface
{
public event EventHandler OnCompleted;
private void CompletedState()
{
OnCompleted?.Invoke(this, new EventArgs());
}
}
public interface IOuterInterface
{
IInnerInterface InnerInterface { get; }
}
public class Main : IOuterInterface
{
public IInnerInterface InnerInterface { get; }
public bool IsOperationComplete { get; set; }
public Main(IInnerInterface innerInterface)
{
InnerInterface = innerInterface;
InnerInterface.OnCompleted += InnerInterface_OnCompleted;
}
private void InnerInterface_OnCompleted(object sender, EventArgs e)
{
IsOperationComplete = true;
}
}
我正在尝试测试主类。测试用例之一是验证事件的处理程序方法。
我尝试了以下代码实现来测试,
[TestClass]
public class MainTest
{
private Mock<IInnerInterface> _innerInterfaceMock;
private Main _main;
[TestInitialize]
public void Initialize()
{
_innerInterfaceMock = new Mock<IInnerInterface>();
_main = new Main(_innerInterfaceMock.Object);
}
[TestMethod]
public void OnCompleted_ShouldDoSomething()
{
//Act
_main.Raise(m=>m.InnerInterface.OnCompleted+=null, new EventArgs());
//Assert
_main.IsOperationComplete.Should().BeTrue();
}
}
我收到以下错误,
Test method Samples.MainTest.OnCompleted_ShouldDoSomething threw exception: Telerik.JustMock.Core.MockException: Unable to deduce which event was specified in the parameter. at Telerik.JustMock.Core.Behaviors.RaiseEventBehavior.RaiseEventImpl(Object instance, EventInfo evt, Object[] args) at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction) at Samples.MainTest.OnCompleted_ShouldDoSomething()
不知道我做错了什么?
最佳答案
您不应从 SUT 引发该事件(主要),直接从 IInnerInterface 模拟中引发它:
_innerInterfaceMock.Raise(o => o.OnCompleted+=null, new EventArgs());
顺便说一句,此代码(基于您的)使用 moq
而不是 justmock
但您的异常与 justmock
相关,我假设同时使用会导致方法和重载困惑,只需选择一个并坚持使用即可。
关于c# - 单元测试: Raise Event From Nested Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547533/