質問

Is there anyway to mock an method that takes a dynamic parameter?

I want to set an expectation like this:

_hasher.Expect(h => h.ComputeHash(Arg<dynamic>.Matches(o=> o.PropertyA == "123"))).Return("some hash");

I get error: An expression tree may not contain a dynamic expression. I can certainly do something like:

_hasher.Expect(h => h.ComputeHash(Arg<object>.Is.Anything)).Return("some hash");

But I feel like this is leaving a gap in my test. Is there any other alternative to mock a dependency that has a method that accepts a dynamic parameter?

役に立ちましたか?

解決

Try this:

_hasher.Expect(h => h.ComputeHash(Arg<object>.Is.Anything)).Return("some hash")
    .WhenCalled(x =>
        {
            dynamic actual = x.Arguments[0];
            Assert.AreEqual("123", actual.PropertyA);
        });

It's a bit of a hack, certainly, but it works, and it gives you useful messages when the tests fail.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top