I'm fairly new to Mockito having gone through their official documentation and a couple of online tutorials in regards to writing tests, as such there is probably something I am missing when I am getting a null returned from a static method I am calling inside a method of a service class under test. I am using Mockito 2.19.0 with assertJ 3.10.0 and the method under test is this:
public Fruit saveFruit(Fruit fruit) {
final String name = fruit.getName().toLowerCase();
Optional<Fruit> fruitOptional = fruitRepository.findOneByName(name);
if (!fruitOptional.isPresent()) {
Fruit newFruit = userDeviceRepository.save(Builder.buildFruitNew(fruit));
LOG.info("saveFruit\t\t->\Fruit saved, {}", newFruit);
return newFruit;
} else {
LOG.info("saveFruit\t\t->\tFruit already exists, updating existing fruit");
Fruit updatedFruit = fruitOptional.map(Builder::buildFruitGet).get();
updatedFruit.setFruitType(fruit.getFruitType());
return fruitRepository.save(updatedFruit);
}
}
The test method I have been trying to write:
@ExtendWith(MockitoExtension.class)
class UserDeviceServiceTest {
@Mock
private FruitRepository fruitRepository;
@InjectMocks
private FruitServiceImpl fruitServiceImpl;
@Test
public void whenSavingNewFruitItShouldReturnTheSavedFruit() {
Fruit newFruit = new Fruit("Lemon", "Yellow");
// Given that a new fruit is saved and returns the new fruit
given(fruitRepository.save(newFruit)).willReturn(newFruit);
// When saving a new fruit
assertThat(fruitServiceImpl.saveFruit(newFruit))
// Then it should return the new fruit
.isSameAs(newFruit);
}
}
When running the test I achieve the following fail message:
java.lang.AssertionError:
Expecting:
<com.fruits.domain.models.Fruit@3bf20acd>
and actual:
<null>
to refer to the same object
EDIT: Added the method I call in the Builder class:
public static Fruit buildFruitNew(Fruit fruit) {
return new Fruit(fruit.getId(), fruit.getType());
}
It seems to me the issue lies with the line where I call the Builder class which contains static methods that return a new instantiated fruit object having had a look at the standard output to see the logger line afterwards which sure enough reports a null object. I have had a read around on here and there was mention PowerMock and JMockit might be needed to test such as class so I assume at the moment it might not possible to test this method because of the static method it uses inside? I know for a fact having already written unit tests for the Builder class that the method used here does return a fruit object with the details of that fruit object passed in so I expected it to run the method without an issue however it seems it doesn't run the method at all. If this is indeed currently not testable code then I imagine if I replaced this static method with a non static method then I would be good to go? Thanks now.