NestorDRod
NestorDRod

Reputation: 166

Evaluate parameter passed to mocked method called from another class

I am testing a class that use another class I have mocked. One of the outer classes' methods modifies an argument that is passed to the mocked class's method, and I need to check that it was modified correctly.

The code looks something like this:

public class Foo
{
  public boolean performTask(String name, Integer version)
  {
    ...
  }
}

public class Bar
{
  private Foo foo;

  public Bar(Foo foo)
  {
    this.foo = foo;
  }

  public void doSomething(String name, Integer version)  
  {  
    boolean good = foo.performTask(name, ((version.startsWith("A")) ? null : version));
    ...
  }
}

I need to check that if I pass a name argument that starts with A, then the second argument being passed to performTask() is null.

Edit:

As requested, this the start of the unit test:

public class BarTest
{
  @Mock
  private Foo mockFoo;

  @Before
  public void setup() throws Exception
  {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void test() throws Exception
  {
    Bar bar = new Bar(mockFoo);

    bar.doSomething("ABC", new Integer(1));
  }
}

Upvotes: 0

Views: 343

Answers (1)

second
second

Reputation: 4259

All the examples I've seen of using verify involve calling the mock class directly. How do I use it in this case?

Exactly like that. All you need is access to the mock, which you have.

Mockito.verify(mockFoo, Mockito.times(1)).performTask("ABC", null);

If its important what the method is supposed to return (by default false), you will need to define the behaviour using:

Mockito.when(mockFoo.performTask("ABC", null)).thenReturn(true);

Example:

@Test
public void test() throws Exception {
    Mockito.when(mockFoo.performTask("ABC", null)).thenReturn(true);

    Bar bar = new Bar(mockFoo);
    bar.doSomething("ABC", new Integer(1));

    Mockito.verify(mockFoo, Mockito.times(1)).performTask("ABC", null);
}

Upvotes: 1

Related Questions