c# - 单元测试: Raise Event From Nested Type

标签 c# unit-testing justmock

我有一个接口(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/

相关文章:

c# - 如何在同一行中找到重复的名称/值?可以算吗?

unit-testing - chalice 2.4.4 : How do mock a transient service inside a domain?

c# - 单元测试遗留代码 : limits of "extract and override" vs JustMock/TypeMock/moles?

c# - SortedDictionary 抛出带有两个不同条目的 "same key already exists"

c# - 我可以创建实体,但无法编辑实体

c# - Moq 返回 null 和 BadRequestObjectResult

testing - 我如何使用 JustMock 来测试接口(interface)事件委托(delegate)

c# - Sitecore 单元测试是不是成功了?

c# - 检查泛型类型是否继承自泛型接口(interface)

perl - 如何在 Perl 中模拟单元测试的子例程?