Spring Boot休息控制器测试

问题描述 投票:0回答:1

我正在为我的控制器编写测试,我已经能够找到搜索端点了。我现在尝试了插入,但没有成功。

我的服务:

public LegalPerson insert(LegalPerson legalPerson) {
        legalPerson.setId(null);
        try {
            legalPerson = repository.save(legalPerson);
        } catch (DataIntegrityViolationException error) {
            throw new DataIntegrity("Error something***", error);
        }
        return legalPerson;
    }

 public LegalPerson modelToEntity(LegalPersonModel personModel) {
        return LegalPerson.builder()
                .active(personModel.getActive())
                .companyId(personModel.getCompanyId())
                .tradeName(personModel.getTradeName())
                .companyName(personModel.getCompanyName())
                .email(personModel.getEmail())
                .cnpj(personModel.getCnpj())
                .stateRegistration(personModel.getStateRegistration())
                .municipalRegistration(personModel.getMunicipalRegistration())
                .openingDate(personModel.getOpeningDate())
                .address(personModel.getAddress())
                .companyType(personModel.getCompanyType())
                .subsidiaries(personModel.getSubsidiaries())
                .phones(personModel.getPhones())
                .build();
    }

我的休息控制器

@RestController
@RequestMapping(value = "/api/clients/lp")
public class LegalPersonResource {

/**other methods ***/
 @PostMapping
    public ResponseEntity<Void> insert(@Valid @RequestBody LegalPersonModel legalPersonModel) {
        var legalPerson = service.modelToEntity(legalPersonModel);
        legalPerson = service.insert(legalPerson);
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(legalPerson.getId()).toUri()).build();
    }

而我的测试

@Test
void insert() throws Exception {
 var mockLPM = new LegalPersonModel(true, 1L, "mockTrade", "mockCompanyName", "mockTest@com", "63.236.885/0001-42", "123455", "1234566", localDate, 1L, CompanyEnum.HEADOFFICE,subsidiaries, phones);
   var objason = new ObjectMapper();
   objason.writeValueAsString(mockLPM);
   var test = mvc.perform(MockMvcRequestBuilders.post("/api/clients/lp").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(String.valueOf(objason))).andReturn();

 int status = test.getResponse().getStatus();
 Assertions.assertEquals(201, status);
}

总是回归状态400.我做错了什么?

====更新:====

它部分工作。

它只适用于ObjectMapper,我必须将LocalDate更改为null,因为它会在一个巨大的字符串中对localDate进行修改:

"openingDate": {"year": 1955, "month": "OCTOBER", "monthValue": 10, "dayOfMonth": 25, "chronology": {"calendarType": "iso8601", "id" "}," era ":" CE "," dayOfYear ": 298," dayOfWeek ":" TUESDAY "," leapYear ": false}

实际上我的json应该是这样的:例如"openingDate": "2019-04-02"

因此,当我将localDate更改为null时,它会传递该部分,但在我的服务的那部分中出现NullPointerException:

var legalPerson = service.modelToEntity (legalPersonModel);

它识别legalPersonModel,这是我们刚刚使用ObjectMapper传递的内容,但legalPerson始终保持为null,它不会被转换。

我尝试了一些没有成功的事情。我该怎么办?

===更新2 ===

如果在其余控制器中,有:

 return ResponseEntity.created (ServletUriComponentsBuilder.fromCurrentRequest (). path ("/ {id}")
                .buildAndExpand (legalPerson.getId ()). toUri ()). build ();

将返回null。

但是,如果我切换到

return ResponseEntity.status (201) .build ();

我有一个绿色测试。

有什么方法可以解决这个问题吗?

spring-boot mockito junit5
1个回答
1
投票

只要你的400 Bad Requesting有效载荷不是有效类型,你就会获得post状态 - 在你的例子中,你应该post一个可以反序列化为LegalPersonModel对象的有效载荷。

您可以直接将有效负载发布为json字符串

@Test
void insertAsJsonString() throws Exception {
    var mockLPM = new LegalPersonModel(true,
            1L,
            "mockTrade",
            "mockCompanyName",
            "mockTest@com",
            "63.236.885/0001-42",
            "123455",
            "1234566",
            localDate,
            1L,
            CompanyEnum.HEADOFFICE,
            subsidiaries,
            phones);

    var om = new ObjectMapper();

    var test = mvc.perform(
            MockMvcRequestBuilders
                    .post("/api/clients/lp")
                    .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                    .content(om.writeValueAsString(mockLPM))
            .andReturn();

    int status = test.getResponse().getStatus();
    Assertions.assertEquals(201, status);
}

要将LocalDate序列化为yyyy-MM-dd格式,请尝试像这样配置ObjectMapper

ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

您可能需要导入jackson-datatype-jsr310。使用maven导入它就像这样

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.8</version>
</dependency>

如果var legalPerson = service.modelToEntity (legalPersonModel);总是导致legalPersonnull,即使LocalDate被正确序列化,你还需要用LegalPerson类更新问题,包括builder模式。


我无法重现“更新2”问题。

鉴于此终点

@PostMapping
public ResponseEntity<Void> insert(@Valid @RequestBody LegalPersonModel legalPersonModel) {
    var legalPerson = service.modelToEntity(legalPersonModel);
    legalPerson = service.insert(legalPerson);
    return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(legalPerson.getId()).toUri()).build();
}

将返回以下内容(使用命令行工具curl

$ curl -X POST -d @legalPersonModelMock 'http://localhost:8080/api/clients/lp'
< HTTP/1.1 201 
< Location: http://localhost:8080/api/clients/lp/1
< Content-Length: 0

legalPersonModelMock文件的内容是jsonvar mockLPM = new LegalPersonModel(...)表示。

你的service.insert(...)代码设置legalPerson.setId(null);,你确定没有弄乱响应吗?

© www.soinside.com 2019 - 2024. All rights reserved.