Can Mockito detect false uses and assignments of fields?

This use case is perhaps best explained by a test:

@Test
public void testZeroInteraction() {
    Pika pika = new Pika();
    Trainer trainer=mock(Trainer.class);

    pika.doNothing3(trainer);
    verifyZeroInteractions(trainer);
}

      

This is my method doNothing3()

in the class Pika

:

void doNothing3(Trainer trainerIn){
    trainer=trainerIn;
    trainerIn.name="Ash";
}

      

In this case, he verifyZeroInteractions()

does not complain and the test passes.

Can Mockito define assignments like those in the method doNothing3

above?

If so, which Mockito method can I use?

+3


source to share


1 answer


OO is behavior , not state.

On the right, the first paragraph in the Mockito documentation reads:

Let's check some behavior! ...

In this sense; when Mokito talks about interaction, what they (or any other mocking framework for my knowledge) mean: method calls.

In other words: the mocked object knows nothing about the fields of the class it is mocking.

So, you could basically do the following:

  • keep the current tag testZeroInteraction()

    (to prove there are no methods )
  • add a second test to check that the real input object doesn't change.


how

@Test
public void testFieldUpdates() {
  Pika pika = new Pika();
  Trainer orig = new Trainer();  
  Trainer copy = new Trainer(orig);
  pika.doNothing3(copy);
  assertThat(orig, is(copy));

      

}

What this test "means": Create a trainer object and then create a copy of it. Pass the first object to your method; and after that check if this object keeps a equals

copy.

But of course this requires that you have some kind of "copy constructor"; as well as a reasonable implementation equals()

.

Finally: you have to start by indenting. My first suggestion is "OO is behavior, not state." Translated to: The idea of ​​having a trainer class with public fields is scent design . You shouldn't be doing this. You don't create objects, pass them in, or add other code to fields. You call methods on other objects, you do not manage their state.

In other words: your approach violates a whole set of important OO principles. And because of this, Mokito does not support what you are doing. Because nobody has to do what you do. So, as said: the real answer here is to fix your broken design.

+2


source







All Articles