【问题标题】:spring boot restcontroller test returns nullspring boot restcontroller 测试返回 null
【发布时间】:2019-04-01 12:28:18
【问题描述】:

我正在测试控制器的“find”方法,它返回“findById”,但返回始终为空。

我的项目结构如下:

我有一个 LegalPerson 实体 扩展 JpaRepository 的存储库

以及“使用”存储库的服务。

@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
class LegalPersonResourceTest {

    @MockBean
    private LegalPersonService service;

    @Autowired
    private MockMvc mvc;

    @Test
    void find() {
        var localDate = LocalDate.of(1955, 10, 25);
        List<Long> subsidiaries = new ArrayList<>() {{
            add(10L);
            add(20L);
        }};
        List<Long> phones = new ArrayList<>() {{
            add(50L);
            add(60L);
        }};
        var mockLP = LegalPerson.builder()
                .id(1L)
                .active(true)
                .companyId(1L)
                .tradeName("Test Company Trade Name")
                .companyName("Test Company Company Name")
                .email("test@com")
                .cnpj("testCNPJ")
                .stateRegistration("test state Registration")
                .municipalRegistration("test Municipal Resgistration")
                .openingDate(localDate)
                .address(1L)
                .companyType(CompanyEnum.HEADOFFICE)
                .subsidiaries(subsidiaries)
                .phones(phones)
                .build();

        Mockito.doReturn(mockLP).when(service).find(1L);
    }
}

我想知道我忘记了什么,或者写错了什么。

编辑 01 :

Mockito.when(this.service.find(ArgumentMatchers.eq(1L))).thenReturn(mockLP);
        mvc.perform(MockMvcRequestBuilders.get("/api/clients/lp/{id}", 1L))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.active", Matchers.is(true)));

完美运行。 但是如果我添加

.andExpect(MockMvcResultMatchers.header().string(HttpHeaders.ETAG, "\"1\""))

返回空值。

【问题讨论】:

  • 你没有测试任何东西。至少不在此处发布的代码中。你只是在做测试设置。

标签: spring-boot mockito junit5


【解决方案1】:

您只是在模拟服务,但没有在此代码中测试任何内容,您可能想要测试控制器,如下所示:

import static org.mockito.BDDMockito.given;

    @Test
    public void shouldGetAPerson() throws Exception {
        //...
        given(service.find(1L)).willReturn(mockLP);
        mvc.perform(MockMvcRequestBuilders.get("/person/1")
                .contentType("application/json"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", Matchers.containsString("1")));
    }

【讨论】:

    【解决方案2】:

    试试ArgumentMatchers

    Mockito.when(this.service.find(ArgumentMatchers.eq(1L)).thenReturn(mockLP);
    

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多