Skip to content
Advertisement

How do I write a test for a service that uses other services in Springboot?

I have a BookManagementService that uses the @Autowired implementation of three other services, like so

JavaScript

So how do I mock the aforementioned services and their repo in the BookManagementServiceTest? When the test start running and it gets to the yearService layer, it throws a NullPointerEXception cause the year it receives is null The BookManagementServiceTest

JavaScript

Advertisement

Answer

You just have to mock all the related services aswell.

Take this as an example, imagine you want to test an ItemService class, that has ItemRepositoy and AuthService autowired.

ItemService.java

JavaScript

Item.java

JavaScript

AuthService.java

JavaScript

ItemRepository.java

JavaScript

ItemServiceTest.java

JavaScript

If you don’t mock the autowired classes and set the when().thenReturn() as you expect you will always get a NullPointException.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement