Markus
Markus

Reputation: 2061

Spring Junit test entity not saved to repository

I'm trying to test a service method that lists all entities. The method looks like this:

@Test
public void listAllProfiles() {
  Profile sampleProfile = Profile.createWithDefaultValues();
  profileRepository.save(sampleProfile);

  ProfileService profileService = new ProfileService(profileRepository, new ModelMapper());
  List<ProfileDto> profiles = profileService.listAllProfiles();
  ProfileDto lastProfile = profiles.get(profiles.size() - 1);

  assertEquals(sampleProfile.getId(), lastProfile.getId());
}

The test fails cause IndexOutOfBoundsException: Index -1 out of bounds for length 0

I found out that the sampleProfile is not probably saved during the test. When I log profileRepository.findAll().size() the value is always 0.

What is worng with my test?

Upvotes: 1

Views: 1519

Answers (1)

Alexis Pavlidis
Alexis Pavlidis

Reputation: 1080

If you want to test your ProfileService you have to mock the profileRepository cause if you don't do that then you are actually doing an integration test.

Unit testing is all about testing small units if there are any dependencies on those units you have to mock them (either manually or with a framework, Mockito is the most common one in the Java world).

If your service is using the repository to fetch all the profiles you have to mock that call, something like this:

 List<Profile> profilesList = Arrays.asList(new Profile("Profile 1"), new Profile("Proiile 2"));
 given(profileRepository.findAll()).willAnswer((Answer<List>) invocation -> profilesList);

So you shouldn't save anything in the database (actually, you shouldn't interact with a database at all when you are unit testing), you just mock the repository you are using on your service. Here is a project I wrote some months ago where I actually solved the exact same issue.

Upvotes: 3

Related Questions