Why a method testing with mockito run (mock ok) but another method in the same class no mock

Viewed 37

I have a Spring Boot Application in Java and I want to test the controller class. The controller class use a service class. I created a listPerson in the test, I mocked the service class and I use the when(.getAPerson).thenReturn(listPersons) and it's ok I have the list of persons created in my test. If I use anotherMethod in the same class the mock not working and I have a empty list.

My Controller is :

// get a person
    @GetMapping(value = "person/{firstNamelastName}")
    public ResponseEntity<List<Persons>> getAPerson(@PathVariable String firstNamelastName, HttpServletRequest request,
            HttpServletResponse response) {

        String elemjson = "persons";
        List<Persons> listP = new ArrayList<>();
        try {
            listP = repositorySafetyNetInterface.getAPerson(firstNamelastName, elemjson);
            if (listP.isEmpty()) {
                response.setStatus(204);
                messagelogger = "No Content. The person does not exist."
                        + loggerApiNewSafetyNet.loggerInfo(request, response, firstNamelastName);
                LOGGER.info(messagelogger);
                return ResponseEntity.status(response.getStatus()).build();
            }
        } catch (IOException e) {
            response.setStatus(404);
            return ResponseEntity.status(response.getStatus()).build();
        } catch (NullPointerException nulle) {
            response.setStatus(404);
            return null;
        }

        messagelogger = "OK" + loggerApiNewSafetyNet.loggerInfo(request, response, firstNamelastName);
        LOGGER.info(messagelogger);
        return new ResponseEntity<>(listP, HttpStatus.valueOf(response.getStatus()));
    }

// add a person @PostMapping(value = "/person") public ResponseEntity addPerson(@RequestBody Persons person, HttpServletRequest request, HttpServletResponse response) {

    List<Persons> listP = new ArrayList<>();
    try {
        listP = repositoryElementJson.getPersons("persons");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    listP = repositorySafetyNetInterface.postPerson(person);

    if (listP.isEmpty()) {
        response.setStatus(404);
        messagelogger = "No persons added. " + RESPONSSTATUS + response.getStatus() + ":"
                + loggerApiNewSafetyNet.loggerInfo(request, response, "");
        LOGGER.info(messagelogger);
        return ResponseEntity.status(response.getStatus()).build();
    }

    response.setStatus(201);
    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{firstName+lastName}")
            .buildAndExpand(person.getFirstName() + person.getLastName()).toUri();
    messagelogger = "A new person is added successful. The URL is : " + location;
    LOGGER.info(messagelogger);
    messagelogger = "Created " + loggerApiNewSafetyNet.loggerInfo(request, response, "");
    LOGGER.info(messagelogger);
    // c'est quoi la différence entre les 2 lignes suivantes created(location).build
    // et
    // https.valuesOf(response.getstatus):
    return new ResponseEntity<>(person, HttpStatus.valueOf(response.getStatus()));
}

My class service :

@Override
public List<Persons> getAPerson(String firstNamelastName, String elemjson) throws IOException {
    List<Persons> listPersons = new ArrayList<>();
    List<Persons> listP = listPersons;
    listPersons = getListsElementsJsonRepository.getPersons(elemjson); // here we have a list of objects Persons
                                                                       // from json

    for (Persons element : listPersons) {
        if ((element.getFirstName().trim() + element.getLastName().trim()).equalsIgnoreCase(firstNamelastName)) {
            listP.add(element);
        }
    }
    LOGGER.debug("Get the person is ok.");
    return listP;
}

@Override
public List<Persons> postPerson(Persons person) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(loggerApiNewSafetyNet.loggerDebug(person.toString()));
    }

    // read the Json File
    List<Persons> listPersons;
    listPersons = createListPersons();

    if (LOGGER.isDebugEnabled()) {
        messageLogger = "The persons are: " + listPersons;
        LOGGER.debug(messageLogger);
    }

    // verify if the persons is exist in the persons if not = add
    boolean findperson = false;
    for (Persons element : listPersons) {
        if ((element.getFirstName() + element.getLastName())
                .equals(person.getFirstName() + person.getLastName())) {
            findperson = true;

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("This person is already in the list.");
            }
            break;
        }
    }

    if (!findperson) {
        Boolean filecreated = false;
        // add the persons if find_persons is false
        listPersons.add(person); // add the body

        if (LOGGER.isDebugEnabled()) {
            messageLogger = "The person is added in the list: " + listPersons;
            LOGGER.debug(messageLogger);
        }

        // create the new file json
        // create list fire stations
        List<Firestations> listFirestations;
        listFirestations = createListFirestations();
        // create list medical records
        List<Medicalrecords> listMedicalrecords;
        listMedicalrecords = createListMedicalrecords();
        newFileJson.createNewFileJson(listPersons, listFirestations, listMedicalrecords, person.toString());
        filecreated = newFileJson.isFileCreated();
        if (Boolean.TRUE.equals(filecreated)) { // return the person from file
            List<Persons> listP;
            listP = verifyIfTheNewPersonInTheFile(person);
            return listP;
        }
    }
    return Collections.emptyList();
}

And my test :

@WebMvcTest(controllers = NewSafetyAlertController.class)
public class NewSafetyAlertControllerTests {

    // Récupération de notre logger.
    private static final Logger LOGGER = LogManager.getLogger(NewSafetyAlertControllerTests.class);

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private SafetyNetInterface safetyNetServiceInterface;


  @Test
    void testAddPerson() throws Exception {
        String firstName = "TEST999_FirstName";
        String lastName = "TEST999_LastName";
        String elemjson = "persons";
        List<Persons> listPersons;
        Persons person;
        person = createPerson(firstName, lastName);
        listPersons = createListPersonsTest(firstName, lastName, person);

        String body = "{\r\n" + "\"firstName\": \"" + firstName + "\",\r\n" + "\"lastName\": \"" + lastName
                + "\",\r\n" + "\"address\": \"1509 Culver St\",\r\n" + "\"city\": \"Culver\",\r\n"
                + "\"zip\": \"97451\",\r\n" + "\"phone\": \"841-874-6512\",\r\n" + "\"email\": \"jaboyd@email.com\"\r\n"
                + "}";
        when(safetyNetServiceInterface.postPerson(person)).thenReturn(listPersons);
        when(safetyNetServiceInterface.getAPerson(firstName + lastName, elemjson)).thenReturn(listPersons);

        mockMvc.perform(post("/person").content(body).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().is(201));

    }

The test is wrong because Expected 201 but was 404.

I use the 2 when...thenReturn because I want see you that the method getAPerson() running but the method addPerson not working.

I don't undestand the mock is ok because the mock run to method getAPerson but it's not orking to the method addPerson.

Thnak you very much Claudiu

0 Answers
Related