[英]TargetParameterCountException in Moq-based unit-test
We have repositories which have a "Save" method. 我们有具有“保存”方法的存储库。 They also throw a "Created" event whenever an entity is saved.
每当保存实体时,它们也会抛出“创建”事件。
We have been trying to use Moq to mock out the repository as such.... 我们一直在尝试使用Moq来模拟存储库......
var IRepository = new Mock<IRepository>();
Request request = new Request();
IRepository.Setup(a => a.Save(request)).Raises(a => a.Created += null, RequestCreatedEventArgs.Empty);
This doesn't seem to work and I always get an exception: 这似乎不起作用,我总是得到一个例外:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
System.Reflection.TargetParameterCountException:参数计数不匹配。
Any example of mocking events with Moq would be helpful. 任何使用Moq模拟事件的例子都会有所帮助。
A standard event type delegate has two arguments usually: a sender object and a subclass-of-EventArgs object. 标准事件类型委托通常有两个参数:sender对象和EventArgs子类对象。 Moq expects this signature from your event, but only finds one argument and this causes the exception.
Moq期望从您的事件中获得此签名,但只发现一个参数,这会导致异常。
Take a look at this code with my comment, it should work: 用我的评论来看看这段代码,它应该有效:
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);
}
It appears that whatever is being returned from RequestCreatedEventArgs.Empty
can't be converted to a RequestCreatedEventArgs
object. 似乎从
RequestCreatedEventArgs.Empty
返回的任何内容都无法转换为RequestCreatedEventArgs
对象。 I would expect the following: 我希望如下:
class IRepository
{
public event THING Created;
}
class THING : EventArgs
{
public static THING Empty
{
get { return new THING(); }
}
}
Verify that THING is the same class in each place in your code as shown above. 如上所示,验证代码中每个位置的THING是否为同一个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.