Home > Mobile >  SpringBoot Test ERROR ( Cannot resolve method 'thenReturn(Entity) )
SpringBoot Test ERROR ( Cannot resolve method 'thenReturn(Entity) )

Time:03-30

Hello i write and backend service that sells flight tickets and i'm trying to write tests for this api. When i try to write createAirlineCompany test for AirlineCompanyController class i get this error.

Cannot resolve method 'thenReturn(flight.flightticketapp.entities.AirlineCompany)'

My test class:

@Test
    public void testCreateAirlineCompany()
    {
        AirlineCompany airlineCompanyNew = new AirlineCompany();
        airlineCompanyNew.setName("RYANAIR");
        when(airlineCompanyService.createAirlineCompany(airlineCompanyNew.getName())).thenReturn(airlineCompanyNew);
        ResponseEntity<AirlineCompany> airlineCompanyResponseEntity = testRestTemplate.postForEntity
                (ROOT_URL "/airlinecompany/airlineCreate",airlineCompanyNew,AirlineCompany.class);
        AirlineCompany airline = (AirlineCompany) airlineCompanyResponseEntity.getBody();
        assertNotNull(airlineCompanyResponseEntity.getBody());
        assertEquals(airlineCompanyNew.getName(),airline.getName());

    }
}

and my AirlineCompanyService class:

@Service
public class AirlineCompanyManager implements AirlineCompanyService {
@Override
    public Result createAirlineCompany(String name) {
        return airlineCompanyAbstract.createAirlineCompany(name);
    }
}

My AirlineCompany Imp class:

@Component
public class AirlineCompanyImp implements AirlineCompanyAbstract {
  @Override
    public Result createAirlineCompany(String name) {
        AirlineCompany airlineCompany = new AirlineCompany();
        airlineCompany.setName(name);
        add(airlineCompany);
        return new SuccessResult(Messages.airlineCompanyCreated);
    }

@Override
    public Result add(AirlineCompany airlineCompany) {

        airlineCompanyRepository.save(airlineCompany);
        return new SuccessResult(Messages.airlineCompanyAdded);
    }

}

The error i got is coming from thenReturn() method and i don't know how to fix this. Thank you for all.

CodePudding user response:

Make sure you have imported correct static methods when()

import static org.mockito.Mockito.when;

CodePudding user response:

You have a mismatch of the return value you use for the mock. When specifying the mock you return an AirlineCompany:

 when(airlineCompanyService.createAirlineCompany(airlineCompanyNew.getName())).thenReturn(airlineCompanyNew);

But your AirlineCompanyService returns a Result:

public Result createAirlineCompany(String name)

Mockito searches for a method returning an AirlineCompany - which does not exist. You have to return a Result from your mock, e. g.

when(airlineCompanyService.createAirlineCompany(airlineCompanyNew.getName())).thenReturn(new Result());
  • Related