代码之家  ›  专栏  ›  技术社区  ›  SharePoint Newbie

基于MOQ的单元测试中的TargetParameterCountException

  •  3
  • SharePoint Newbie  · 技术社区  · 16 年前

    我们有具有“保存”方法的存储库。它们还在保存实体时抛出“已创建”事件。

    我们一直在尝试使用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: 参数计数不匹配。

    任何用moq模拟事件的例子都是有帮助的。

    2 回复  |  直到 13 年前
        1
  •  3
  •   Massimiliano    16 年前

    标准事件类型委托通常有两个参数:发送方对象和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);
        }
    
        2
  •  0
  •   Taryn Frank Pearson    13 年前

    似乎任何东西都是从 RequestCreatedEventArgs.Empty 无法转换为 RequestCreatedEventArgs 对象。我预计会出现以下情况:

    class IRepository
    { 
        public event THING Created; 
    }
    class THING : EventArgs
    { 
        public static THING Empty 
        { 
            get { return new THING(); } 
        } 
    }
    

    验证代码中每个地方的类是否相同,如上图所示。

    推荐文章