2

我有一个接口,它在另一个接口上有一个属性,

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;
    }
}

我正在尝试测试 Main 类。测试用例之一是验证事件的 Handler 方法。

我尝试了以下代码实现来测试,

[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();

    }
}

我收到以下错误,

测试方法 Samples.MainTest.OnCompleted_ShouldDoSomething 抛出异常:Telerik.JustMock.Core.MockException:无法推断参数中指定了哪个事件。在 Telerik.JustMock.Core.Behaviors.RaiseEventBehavior.RaiseEventImpl(Object instance, EventInfo evt, Object[] args) 在 Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction) 在 Samples.MainTest.OnCompleted_ShouldDoSomething()

不知道我做错了什么?

4

1 回答 1

3

你不应该从你的SUT(主)中引发事件,直接从 IInnerInterface 模拟中引发它:

_innerInterfaceMock.Raise(o => o.OnCompleted+=null, new EventArgs());

顺便说一句,这段代码(基于你的)moq没有使用,justmock但你的异常是justmock相关的,我假设同时使用会导致方法和重载混淆,只需选择一个并坚持下去。

于 2018-01-31T17:19:14.400 回答