【问题标题】:Cannot solve Assertion Failed Error with Expected and Actual无法用预期和实际解决断言失败错误
【发布时间】:2022-12-03 07:32:28
【问题描述】:

通过 Id 为其控制器类检索特定有机猫来创建 TDD,但断言失败。在控制器类中,该方法被写为;

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);
    }
}

对于 Controller 测试类中的方法;

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);
    }

}

运行测试时,我会得到一个错误;

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>


    

我在方法中添加了 Optional,但是出现了这个错误。不确定我可以选择哪些其他路线。我是 Spring REST API 的新手。

【问题讨论】:

    标签: java json intellij-idea spring-rest


    【解决方案1】:

    Assertion Failed 错误消息表示预期结果和实际结果在您的代码中不匹配。这通常意味着您正在测试的代码没有按预期工作,或者您的测试没有正确验证代码的输出。

    在您发布的代码中,错误可能发生在以下几行中:

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

    assertThat 方法用于将预期结果(第一个参数)与实际结果(调用该方法的对象)进行比较。在这种情况下,使用 contains 方法将结果与 testOrganicCat 进行比较。如果结果不包含 testOrganicCat,则断言将失败。

    要修复此错误,您可以修改您正在测试的代码以确保它返回预期结果,或者您可以修改您的测试以更好地匹配实际结果。例如,您可以将 contains 方法更改为 containsExactly 方法,以将结果集合中的确切元素与 testOrganicCat 对象进行比较,而不仅仅是检查 testOrganicCat 是否是结果的成员。

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

    我希望这有帮助!如果您有任何其他问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 2019-08-16
      • 2023-03-22
      • 2012-11-28
      相关资源
      最近更新 更多