user4422
user4422

Reputation: 21

Stubbing methods in Java

I am coming from a ruby/rails background and am trying to test with JUnit a Java project that I am working on.

I am looking for a library similar to Mocha with Rspec but for Java.

What exactly I am trying to do is something similar to this:

Model.any_instance.stubs(:method).returns('foo').

The goal being to stub the answer of any call to a method for the given instance of a class.

Any idea? I looked at Mockito, but could not find a way to do this.

Thanks

Upvotes: 2

Views: 782

Answers (3)

feech
feech

Reputation: 424

try anystub. it's for switchers from rails.

Upvotes: 0

Baptiste
Baptiste

Reputation: 21

You can look EasyMock Framework, it's very easy to use and have a good community. You can find documentation here EasyMock documentation

Upvotes: 2

Rob Trickey
Rob Trickey

Reputation: 1311

With Mockito you can do

MyClass myObj = mock(MyClass.class);
when(myObj.callMyMethod(any(Integer.class)).thenReturn("foo");

providing callMyMethod takes an Integer, and returns a String.

You can specify exact arguments instead of any(???.class) if you'd rather be more specific.

Upvotes: 3

Related Questions