其他分享
首页 > 其他分享> > 基于Moq的单元测试中的TargetParameterCountException

基于Moq的单元测试中的TargetParameterCountException

作者:互联网

我们的存储库具有“保存”方法.每当保存实体时,它们还会引发“已创建”事件.

我们一直在尝试使用Moq来模拟存储库.

var IRepository = new Mock<IRepository>();
Request request = new Request();
IRepository.Setup(a => a.Save(request)).Raises(a => a.Created += null, RequestCreatedEventArgs.Empty);

这似乎不起作用,我总是遇到一个例外:

System.Reflection.TargetParameterCountException:
Parameter count mismatch.

使用Moq模拟事件的任何示例都将有所帮助.

解决方法:

标准事件类型委托通常具有两个参数:发送者对象和EventArgs的子类. Moq希望从您的事件中获得此签名,但是只能找到一个参数,这会导致异常.

用我的注释看一下这段代码,它应该可以工作:

    public class Request
    {
        //...
    }

    public class RequestCreatedEventArgs : EventArgs
    { 
        Request Request {get; set;} 
    } 

    //=======================================
    //You must have sender as a first argument
    //=======================================
    public delegate void RequestCreatedEventHandler(object sender, RequestCreatedEventArgs e); 

    public interface IRepository
    {
        void Save(Request request);
        event RequestCreatedEventHandler Created;
    }

    [TestMethod]
    public void Test()
    {
        var repository = new Mock<IRepository>(); 
        Request request = new Request();
        repository.Setup(a => a.Save(request)).Raises(a => a.Created += null, new RequestCreatedEventArgs());

        bool eventRaised = false;
        repository.Object.Created += (sender, e) =>
        {
            eventRaised = true;
        };
        repository.Object.Save(request);

        Assert.IsTrue(eventRaised);
    }

标签:exception,moq,c,net
来源: https://codeday.me/bug/20191210/2102475.html