Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - Can I use Moq to verify that a mocked method was called with specific values in a complex parameter?

So assume I am mocking the following class:

public class ClassAParams
{
    public int RequestedId { get; set; }
    public string SomeValue { get; set; }
}

public class ClassA
{
    public void ExecuteAction(ClassAParams executeParams) {}
}

Now say I have another class (let's call it ClassB) that I am creating a unit testing for, and I want to make sure that when ClassB.Execute() is called, that ClassB calls ClassA.ExecuteAction() but I want to make sure that the parameter it calls that method with has a ClassAParams.RequestedId value of 1.

Normally, I would handle this by doing myMock.Verify(x => x.ExecuteAction(new ClassAParams { RequestedId = 1, SomeValue = "something" }));

The problem is, I do not want to check the value of the SomeValue parameter, or any other ClassAParams properties in this unit test. The other properties will be checked in other unit tests, but having to verify that it's called with the correct properties in every unit test (even when I don't care in the scope of a specific unit tests) will make unit maintenance annoying.

Is there any way to use Moq to verify that the structure that gets passed into a mocked method only has certain properties as a specific value, and ignore the rest?

question from:https://stackoverflow.com/questions/6317350/can-i-use-moq-to-verify-that-a-mocked-method-was-called-with-specific-values-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An overload exists for mock.Verify which allows you to test something. Here is an example that should work for your test.

classA.Verify(
    a => a.ExecuteAction(
        It.Is<ClassAParams>(p => p.RequestedId == 12)
    )
);

Which means "For any ClassAParams passed as argument, verify RequestId equals 12".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...