martes, 3 de julio de 2012

EasyMock & Matchers

Hi there!

If you are down this rode chances are you were looking for something related to EasyMock right??
In short (for those who don't know) EasyMock is a mocking framework, makes sense ah?

I suggest you check mocking in Wikipedia, you are lost at this point.

For the rest of you here is the actual point of this post.
Haven you ever find your self mocking a method call where you know ALMOST ALL the values of the parameters that the method would be receiving. Please note that I set almost.

Well thing is, for those values we don't know Easy Mock provide us with matchers. It is a way to say "hey you're going to be receiving, let's say, a String".
Don't really know which one, don't know the content of it and I JUST DON'T CARE.

Here is how you can do that:

The method firm: public void myMetod(String firstStr, String secondStr)


Easy mock call: EasyMock.expects(obj.myMethod("", EasyMock.anyObject(String.class)); 

Now this makes sense right!!!!
BUT IT DOESN'T

You see, although I'm not laying to you, and Easy Mock does allow you to do such things the above it's not the correct way.
EasyMock allow you to use matchers in your method call BUT
Either all the parameters are passed through Matchers or not. You can't have mixed things as before.

So here are two valid calls:

EasyMock.expects(obj.myMethod(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class)); EasyMock.expects(obj.myMethod("", ""); 
Now all this brings us to the main problem:

What if I know some of the value an I don't know some of them. More important I don't know some of the values but at least one must be a particular value.

Well Easy Mock does also provide you with a way to do that, by the use of the following matcher:

EasyMock.eq("");

So the invalid call above should turn into this:

EasyMock.expects(obj.myMethod(EasyMock.eq(""), EasyMock.anyObject(String.class)); 

In this way you can keep on mocking.

For those of you that may be googling this article the exception thrown when doing this is:


java.lang.IllegalStateException: 2 matchers expected, 1 recorded.

Any way, I hope you have enjoy this!
Please also check this article that help me to find out this

No hay comentarios:

Publicar un comentario