Zookey
Zookey

Reputation: 2707

How to test presenter method that create a new object inside it?

I have this method to validate Unit. I send field values and inside it method I create a new model and then return that model via interface.

public void validate(String unitNumber, Integer unitTypeId, String notes) {
if(!TextUtils.isEmpty(unitNumber)) {
      Unit unit = new Unit();
      unit.setUnitNumber(unitNumber);
      unit.setFlatTypeId(unitTypeId);
      unit.setNotes(notes);
      view.displayUnitValid(unit);
    } else {
      view.displayUnitNotValid();
    }
  }

Now I want do do unit testing of this method with the following code.

@Test public void shouldValidateSinceUnitNumberIsValid() {
    // Given
    String unitNumber = "1";

    // When
    presenter.validate(unitNumber, null, null);

    // Then
    Mockito.verify(view).displayUnitValid(new Unit());
 }

I am getting the following error message:

Argument(s) are different! Wanted:
view.displayUnitValid(
    com.rwar.domain.customers.Unit@57cf54e1
);
-> at com.rwar.presentation.work_orders.AddUnitPresenterTest.shouldValidateSinceUnitNumberIsValid(AddUnitPresenterTest.java:73)

Obvisouly there is a problem since I am creating a new Unit instance here:

Mockito.verify(view).displayUnitValid(new Unit());

And inside validate() method I create another instance of Unit.

How I can fix this?

Upvotes: 0

Views: 276

Answers (3)

Javier Herrero
Javier Herrero

Reputation: 91

In case you want to do this in Kotlin, you can use Mockito check function to make asserts over the Unit instance that is passed as an argument of displayUnitValid(). Something like this:

Mockito.verify(view).displayUnitValid(Mockito.check { unit ->
    assertEquals(unitNumber, unit.getUnitNumber)
});

More info about check here

Upvotes: 1

Zookey
Zookey

Reputation: 2707

Here is the working solution that might be useful to someone else:

 @Test public void shouldValidateSinceUnitNumberIsValid() {
    // Given
    String unitNumber = "1";

    // When
    presenter.validate(unitNumber, null, null);

    // Then use ArgumentCaptor to get unit value from newly created object inside validate() method
    ArgumentCaptor<Unit> argument = ArgumentCaptor.forClass(Unit.class);
    Mockito.verify(view).displayUnitValid(argument.capture());
    // Compare captured argument of Unit number with local unitNumber
    assertEquals(argument.getValue().getUnitNumber(), unitNumber);
  }

Upvotes: 1

darken
darken

Reputation: 816

Pass the same arguments to your verifying method, e.g.

Unit expected = new Unit()
unit.setUnitNumber(unitNumber);
unit.setFlatTypeId(unitTypeId);
unit.setNotes(notes);
Mockito.verify(view).displayUnitValid(expected);

You'll likely have to override your Unit classes equals/hashcode method such that they compare their contents and not the instance itself.

Upvotes: 2

Related Questions