Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing method parameter in jMock to pass to a stubbed implementation

I wish to achieve the following behavior. My class under test has a dependency on some other class, I wish to mock this dependency with jMock. Most of the methods would return some standard values, but there is one method, where I wish to make a call to a stubbed implementation, I know I can call this method from the will(...) but I want the method to be called by the exact same parameters that were passed to the mocked method.

Test

@Test
public void MyTest(){
    Mockery context = new Mockery() {
        {
            setImposteriser(ClassImposteriser.INSTANCE);
        }
    };
    IDependency mockObject = context.mock(IDependency.class);
    Expectations exp = new Expectations() {         
        {
            allowing(mockObject).methodToInvoke(????);
            will(stubMethodToBeInvokedInstead(????));
        }       
    };      
}

Interface

public interface IDependency {
    public int methodToInvoke(int arg);
}

Method to be called instead

public int stubMethodToBeInvokedInstead(int arg){
    return arg;
}

So how do I capture the parameter that were passed to the method being mocked, so I could pass them to the stubbed method instead?

EDIT

Just to give another example, let's say I wish to mock the INameSource dependency in the following (C#) code, to test the class Speaker

public class Speaker
{
  private readonly string firstName;
  private readonly string surname;
  private INameSource nameSource ;
 public Speaker(string firstName, string surname, INameSource nameSource)
  {
    this.firstName = firstName;
    this.surname = surname;
    this.nameSource = nameSource;
  }
  public string Introduce()
  {
    string name = nameSource.CreateName(firstName, surname);
    return string.Format("Hi, my name is {0}", name);
  }
}
public interface INameSource
{
  string CreateName(string firstName, string surname);
}

This is how it can be done in Rhino Mocks for C# I understand it can't be as easy as this since delegates are missing in Java

like image 267
Jugal Thakkar Avatar asked Aug 31 '12 07:08

Jugal Thakkar


2 Answers

The solution from Duncan works well, but there is even a simpler solution without resort to a custom matcher. Just use the Invocation argument that is passed to the CustomActions invoke method. At this argument you can call the getParameter(long i) method that gives you the value from the call.

So instead of this

return matcher.getLastValue();

use this

return (Integer) invocation.getParameter(0);

Now you don't need the StoringMatcher anymore: Duncans example looks now like this

@RunWith(JMock.class)
public class Example {

  private Mockery context = new JUnit4Mockery();

  @Test
  public void Test() {

    final IDependency mockObject = context.mock(IDependency.class);

    context.checking(new Expectations() {
      {
        // No custom matcher required here
        allowing(mockObject).methodToInvoke(with(any(Integer.class)));

        // The action will return the first argument of the method invocation.
        will(new CustomAction("returns first arg") {
          @Override
          public Object invoke(Invocation invocation) throws Throwable {
            return (Integer) invocation.getParameter(0);
          }
        });
      }
    });

    Integer test1 = 1;
    Integer test2 = 1;

    // Confirm the object passed to the mocked method is returned
    Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
    Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
  }

  public interface IDependency {
    public int methodToInvoke(int arg);
  }
like image 158
Ewaryst Schulz Avatar answered Nov 03 '22 01:11

Ewaryst Schulz


Like Augusto, I'm not convinced this is a good idea in general. However, I couldn't resist having a little play. I created a custom matcher and a custom action which store and return the argument supplied.

Note: this is far from production-ready code; I just had some fun. Here's a self-contained unit test which proves the solution:

@RunWith(JMock.class)
public class Example {

  private Mockery context = new JUnit4Mockery();

  @Test
  public void Test() {

    final StoringMatcher matcher = new StoringMatcher();
    final IDependency mockObject = context.mock(IDependency.class);

    context.checking(new Expectations() {
      {
        // The matcher will accept any Integer and store it
        allowing(mockObject).methodToInvoke(with(matcher));

        // The action will pop the last object used and return it.
        will(new CustomAction("returns previous arg") {
          @Override
          public Object invoke(Invocation invocation) throws Throwable {
            return matcher.getLastValue();
          }
        });
      }
    });

    Integer test1 = 1;
    Integer test2 = 1;

    // Confirm the object passed to the mocked method is returned
    Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
    Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
  }

  public interface IDependency {
    public int methodToInvoke(int arg);
  }

  private static class StoringMatcher extends BaseMatcher<Integer> {

    private final List<Integer> objects = new ArrayList<Integer>();

    @Override
    public boolean matches(Object item) {
      if (item instanceof Integer) {
        objects.add((Integer) item);
        return true;
      }

      return false;
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("any integer");
    }

    public Integer getLastValue() {
      return objects.remove(0);
    }
  }
}

A Better Plan

Now that you've provided a concrete example, I can show you how to test this in Java without resorting to my JMock hackery above.

Firstly, some Java versions of what you posted:

public class Speaker {
  private final String firstName;
  private final String surname;
  private final NameSource nameSource;

  public Speaker(String firstName, String surname, NameSource nameSource) {
    this.firstName = firstName;
    this.surname = surname;
    this.nameSource = nameSource;
  }

  public String introduce() {
    String name = nameSource.createName(firstName, surname);
    return String.format("Hi, my name is %s", name);
  }
}

public interface NameSource {
  String createName(String firstName, String surname);
}

public class Formal implements NameSource {
  @Override
  public String createName(String firstName, String surname) {
    return String.format("%s %s", firstName, surname);
  }    
}

Then, a test which exercises all the useful features of the classes, without resorting to what you were originally asking for.

@RunWith(JMock.class)
public class ExampleTest {

  private Mockery context = new JUnit4Mockery();

  @Test
  public void testFormalName() {
    // I would separately test implementations of NameSource
    Assert.assertEquals("Joe Bloggs", new Formal().createName("Joe", "Bloggs"));
  }

  @Test
  public void testSpeaker() {
    // I would then test only the important features of Speaker, namely
    // that it passes the right values to the NameSource and uses the
    // response correctly
    final NameSource nameSource = context.mock(NameSource.class);
    final String firstName = "Foo";
    final String lastName = "Bar";
    final String response = "Blah";

    context.checking(new Expectations() {
      {
        // We expect one invocation with the correct params
        oneOf(nameSource).createName(firstName, lastName);
        // We don't care what it returns, we just need to know it
        will(returnValue(response));
      }
    });

    Assert.assertEquals(String.format("Hi, my name is %s", response),
        new Speaker(firstName, lastName, nameSource).introduce());
  }
}
like image 1
Duncan Jones Avatar answered Nov 03 '22 01:11

Duncan Jones