Home > other >  Service layer unit testing spring boot
Service layer unit testing spring boot

Time:07-25

I want to test my service layer but stuck with an error. I have Company entity and createCompany method in my service

    public Company createCompany(String name) {
        Optional<Company> existingCompany = companyRepository.findCompanyByName(name);
        if (existingCompany.isPresent()) {
            log.error("Company with name {} already exists", name);
            throw new ValidationException("Company with name "   name   " already exists");
        } else {
            return companyRepository.save(new Company(UUID.randomUUID(), name, new HashSet<>()));
        }
    }

Here's my test:

    @Test
    public void whenCreateCompany_thenReturnCompany() {
        // prepare
        Company company = new Company();
        when(companyRepository.save(any())).thenReturn(company);

        // testing
        Company createdCompany = companyService.createCompany("name");

        // validate
        verify(companyRepository).save(company);
    }

But when I run test, I get an error

Argument(s) are different! Wanted:
companyRepository.save(
    Company(id=null, name=null)
);
Actual invocations have different arguments:
companyRepository.findCompanyByName(
    "name"
);

companyRepository.save(
    Company(id=f7cf1525-0dc4-4c27-a9af-693e2a295437, name=name)
);

How to test the service level correctly?

CodePudding user response:

You can change your when call to using org.mockito.ArgumentMatchers.any() as parameter instead of your empty company object.

 when(companyRepository.save(any())).thenReturn(company);

In your code mockito expects your, in the test created, company object passed in the save method. But your manually company contains id and name as null values. But in your test you try to save a company with the name=name and a random generated uuid.

Update from comments: You have to use any in the verify method, too.

verify(companyRepository).save(any());
  • Related