Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moq does not distinguish between distinct events if they have the same name #893

Closed
stakx opened this issue Aug 16, 2019 · 0 comments · Fixed by #914
Closed

Moq does not distinguish between distinct events if they have the same name #893

stakx opened this issue Aug 16, 2019 · 0 comments · Fixed by #914
Assignees
Labels
Milestone

Comments

@stakx
Copy link
Contributor

stakx commented Aug 16, 2019

Code to reproduce:

[Fact]
public void Moq_can_distinguish_between_two_events_having_same_name()
{
    var ab = new Mock<object>();
    var a = ab.As<IA>();
    var b = ab.As<IB>();

    var aeRaiseCount = 0;
    (a.Object).E += () => aeRaiseCount++;

    var beRaiseCount = 0;
    (b.Object).E += () => beRaiseCount++;

    a.Raise(m => m.E += null);
    Assert.Equal(1, aeRaiseCount);
    Assert.Equal(0, beRaiseCount);

    b.Raise(m => m.E += null);
    Assert.Equal(1, aeRaiseCount);
    Assert.Equal(1, beRaiseCount);
}

public interface IA
{
    event Action E;
}

public interface IB
{
    event Action E;
}

public class AB : IA, IB
{
    private Action ae;
    private Action be;

    event Action IA.E
    {
        add => this.ae = (Action)Delegate.Combine(this.ae, value);
        remove => this.ae = (Action)Delegate.Combine(this.ae, value);
    }

    event Action IB.E
    {
        add => this.be = (Action)Delegate.Combine(this.be, value);
        remove => this.be = (Action)Delegate.Combine(this.be, value);
    }

    public void RaiseAE() => this.ae?.Invoke();

    public void RaiseBE() => this.be?.Invoke();
}

Expected outcome:

The above test should pass, since IA.E and IB.E implemented by AB are two distinct events.

Actual outcome:

The test fails because Moq treats both events as one and the same.

Additional details:

This is a direct consequence of Moq identifying events by name only, see e.g.:

https://github.com/moq/moq4/blob/0307f25564e75d68f0fc189f4d8c8c800b59f98e/src/Moq/Interception/InterceptionAspects.cs#L209-L263

EventHandlerCollection likewise uses event names as its keys. Using EventInfo would be more correct, but care would have to be taken to properly deal with polymorphism.

@stakx stakx added the bug label Aug 16, 2019
@stakx stakx added this to the 4.13.1 milestone Aug 16, 2019
@stakx stakx self-assigned this Aug 16, 2019
@stakx stakx modified the milestones: 4.13.1, 4.13.0 Aug 31, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant