Home > Software engineering >  Cannot solve Assertion Failed Error with Expected and Actual
Cannot solve Assertion Failed Error with Expected and Actual

Time:12-03

Creating a TDD with retrieving a specific Organic Cat by Id for its controller class, but assertion failed. Within the controller class the method is written as;

package com.example.VirtualPetAPI.controllers;

import com.example.VirtualPetAPI.models.OrganicCat;
import com.example.VirtualPetAPI.repos.OrganicCatRepository;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Optional;

@RestController
@CrossOrigin
public class OrganicCatRestController {
    @Resource
    private OrganicCatRepository organicCatRepo;
    @GetMapping("/api/organicCats")
    public Collection<OrganicCat> getOrganicCats(){
        return (Collection<OrganicCat>) organicCatRepo.findAll();
    }
    @GetMapping("api/organicCats{organicCatId}")
    public Optional<OrganicCat> getOrganicCat(@PathVariable Long id) {
        return organicCatRepo.findById(id);
    }
}

for methods within the Controller test class;

package com.example.VirtualPetAPI;

import com.example.VirtualPetAPI.controllers.OrganicCatRestController;
import com.example.VirtualPetAPI.models.OrganicCat;
import com.example.VirtualPetAPI.models.Shelter;
import com.example.VirtualPetAPI.models.Volunteer;
import com.example.VirtualPetAPI.repos.OrganicCatRepository;
import com.example.VirtualPetAPI.repos.ShelterRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class OrganicCatControllerTest {
    @Mock
    private ShelterRepository shelterRepo;
    @Mock
    private OrganicCatRepository organicCatRepo;
    @InjectMocks
    private OrganicCatRestController underTest;
    private OrganicCat testOrganicCat;
    private Shelter testShelter;
    private Volunteer testVolunteer;

    @BeforeEach
    public void setUp(){
        MockitoAnnotations.openMocks(this);
        testOrganicCat = new OrganicCat("TestOrganicCatName", "TestOrganicCatStatus",testShelter,(List<Volunteer>) testVolunteer);
    }
    @Test
    public void shouldReturnAllOrganicCats(){
        when(organicCatRepo.findAll()).thenReturn(Collections.singletonList(testOrganicCat));
        Collection<OrganicCat> result = underTest.getOrganicCats();
    }
    @Test
    public void fetchAllEndpointReturnsAllOrganicCats() throws Exception{
        when(organicCatRepo.findAll()).thenReturn(Collections.singletonList(testOrganicCat));
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(underTest).build();
        mockMvc.perform(get("/api/organicCats"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0].name",is("TestOrganicCatName")));

    }
    @Test
    public void retrieveByIdShouldReturnASpecificOrganicCatById(){
        when(organicCatRepo.findById(1L)).thenReturn(Optional.of(testOrganicCat));
        Optional<OrganicCat> result = underTest.getOrganicCat(1L);
        assertThat(result).isEqualTo(testOrganicCat);
    }

}

When running the test, I would get an error of;

org.opentest4j.AssertionFailedError: 
expected: com.example.VirtualPetAPI.models.OrganicCat@1f
 but was: Optional[com.example.VirtualPetAPI.models.OrganicCat@1f]
Expected :com.example.VirtualPetAPI.models.OrganicCat@1f
Actual   :Optional[com.example.VirtualPetAPI.models.OrganicCat@1f]
<Click to see difference>


    

I added Optional to the method, but this error occurs. Not sure what other routed I can go with. I am new to Spring REST API.

CodePudding user response:

The Assertion Failed error message indicates that the expected result and actual result do not match in your code. This usually means that either the code you are testing is not working as expected, or your test is not correctly verifying the code's output.

In the code you posted, the error is likely occurring in the following lines:

Collection<OrganicCat> result = underTest.getOrganicCats();
assertThat(result).contains(testOrganicCat);

The assertThat method is used to compare the expected result (the first argument) with the actual result (the object the method is called on). In this case, result is being compared to testOrganicCat using the contains method. If result does not contain testOrganicCat, then the assertion will fail.

To fix this error, you can either modify the code you are testing to ensure that it returns the expected result, or you can modify your test to better match the actual result. For example, you could change the contains method to the containsExactly method to compare the exact elements in the result collection to the testOrganicCat object, rather than just checking if testOrganicCat is a member of result.

Collection<OrganicCat> result = underTest.getOrganicCats();
assertThat(result).containsExactly(testOrganicCat);

I hope this helps!

  • Related