开发者

NMock - how to say expect 'any value' on these params? Or should I not do this?

开发者_StackOverflow

I have a quick question that I could not figure out in the docs about NMock2.0.

I have a function called Save() that I want to mock out. This takes a string ID as parameter and a decimal as value..

I know I can write this to make sure that Save() gets called with 2 specific values:

    Expect.Once.On(dao) _
    .Method("Save").With(New Object() {"foo", 1})

But this only passes if "foo" and 1 are passed. I do have control of the value "foo", but for the second value, I don't know what it will be; or I don't care about testing what it's value will be at least in this specific test.

I know I can write:

    Expect.Once.On(dao) _
    .Method("Save").WithAnyArguments()

But this will allow me to pass any arguements; so if Save interface changes and later takes 5 parameters, my test will still pass.

How can I make sure it only takes the 2 params, with their proper types?

Perhaps more importantly - is writing a unit test like this too brittle? Maybe I should code it to expect any params, so that each time I refactor I do not have to come back and change that line? I have found that my test cases which use lots of mocks are very brittle and anytime I refactor I have to change them... Maybe I am mis-using mocks here? Still pretty new to this stuff, so any advice is greatly appreciated.


Use the Is.TypeOf() matcher to match a specific type without regard for its value. You want something like:

Expect.Once.On(dao).Method("Save").With(Is.TypeOf(typeof(string)));

As for whether it's reasonable or not, I'd say this is fine in the general case if you're trying to verify that a method can deal with parameters of its specified input types. For example, say you pass in a Car to a method that expects a Vehicle; it will be useful to make sure that the method can handle derived types correctly.


You can create a simple class:

class DontCare
{
    public override bool Equals(object obj)
    {
        return true;
    }
}

Expect.Once.On(dao).Method("Save").With(new DontCare());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜