TargetParameterCountException in Moq-based Unit Test

We have repositories that have a save method. They also throw the "Created" event whenever an object is saved.

We tried to use Moq to shred the repository per se ....

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

This does not work, and I always get an exception:

System.Reflection.TargetParameterCountException: Parameter counter mismatch.

Any example of mocking events using Moq would be helpful.

+3
source share
2 answers

: - -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);
    }
+3

, , RequestCreatedEventArgs.Empty, RequestCreatedEventArgs. :

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

, THING , .

0

Source: https://habr.com/ru/post/1714164/


All Articles