该错误在Springboot Controller测试期间解决了,但我不知道原因

发布于 2025-02-06 03:34:39 字数 3900 浏览 1 评论 0原文

在Springboot Controller测试期间解决了该错误,但我不知道原因

测试环境

  • Java 8
  • Spring Boot
  • Intellij
  • H2DB

以下是控制器阶段的代码。

private MonsterEntity defaultMonster = MonsterEntity.builder()
            .id(1L)
            .monsterLevel(BABY)
            .monsterType(FLY)
            .statusCode(StatusCode.HEALTHY)
            .ssn("12345612345123")
            .name("BabyMonster")
            .age(3)
            .height(170)
            .weight(73)
            .build();

private CreateMonsterDto.Request getCreateRequest() {
            return CreateMonsterDto.Request.builder()
                    .id(1L)
                    .monsterLevel(BABY)
                    .monsterType(FLY)
                    .statusCode(StatusCode.HEALTHY)
                    .ssn("12345612345123")
                    .name("BabyMonster")
                    .age(3)
                    .height(170)
                    .weight(73)
                    .build();
}

@Test
@DisplayName("Monster Created Test")
void createMonster() throws Exception {
    given(mMakerService.createMonster(getCreateRequest()))
            .willReturn(CreateMonsterDto.TestResponse.fromEntity(defaultMonster));
    
    CreateMonsterDto.Response result = mMakerService.createMonster(getCreateRequest());
    
    mockMvc.perform(
                    post("/create-monster")
                            .contentType(contentType)
                            .content(new ObjectMapper().writeValueAsString(result)))
            .andExpect(status().isOk())
            .andDo(print())
            .andReturn();
    then(mMakerService).should(times(2)).createMonster(getCreateRequest());
}

给定(mmakerservice.createmonster(getCreaterequest())) and

createMonstto.Response结果= mmakerservice.createmonster(getCreateAterequest(getCreateAterequest());

所有这些都在返回相同的无效值。

解决此问题的解决方案是将@EqualsAndHashCode注释添加到DtoreQuest。

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@EqualsAndHashCode(of = "id")
public static class Request {

    @NotNull
    private Long id;

    @NotNull
    private MonsterLevel monsterLevel;

    @NotNull
    private MonsterType monsterType;

    @NotNull
    private StatusCode statusCode;

    @NotNull
    @Size(min = 13, max = 15, message = "ssn max_size 14")
    private String ssn;

    @NotNull
    @Size(min = 3, max = 100, message = "name size must 3~100")
    private String name;

    @NotNull
    @Min(0)
    @Max(100)
    private Integer age;

    @NotNull
    @Min(150)
    @Max(300)
    private Integer height;

    @NotNull
    @Min(50)
    @Max(500)
    private Integer weight;
}

mmakerservice.createmonster(getCreaterequest());是通过从地址参考值而不是内容中取出?

以下是服务阶段的代码。

public CreateMonsterDto.Response createMonster(
            CreateMonsterDto.Request request
    ) {
    validateCreateMonsterRequest(request);

    return CreateMonsterDto.Response.fromEntity(
            monsterRepository.save(
                    createMonsterFromRequest(request)
            )
    );
}

private MonsterEntity createMonsterFromRequest(CreateMonsterDto.Request request) {
   return MonsterEntity.builder()
        .id(1L)
        .monsterLevel(request.getMonsterLevel())
        .monsterType(request.getMonsterType())
        .statusCode(request.getStatusCode())
        .ssn(request.getSsn())
        .name(request.getName())
        .age(request.getAge())
        .height(request.getHeight())
        .weight(request.getWeight())
        .build();
}

当我在ServiceTest上运行这个过程时,没有问题。

我想知道这个问题的原因。帮助。对不起,问题不好。我正在使用翻译器。

我在调试时正在寻找问题,但是当我在ControlerTest进行调试时,直到服务阶段才能调试...

The error was resolved during the springboot controller test, but I don't know the cause

test environment

  • JAVA 8
  • SPRING BOOT
  • INTELLIJ
  • H2DB

Below is the code of the controller stage.

private MonsterEntity defaultMonster = MonsterEntity.builder()
            .id(1L)
            .monsterLevel(BABY)
            .monsterType(FLY)
            .statusCode(StatusCode.HEALTHY)
            .ssn("12345612345123")
            .name("BabyMonster")
            .age(3)
            .height(170)
            .weight(73)
            .build();

private CreateMonsterDto.Request getCreateRequest() {
            return CreateMonsterDto.Request.builder()
                    .id(1L)
                    .monsterLevel(BABY)
                    .monsterType(FLY)
                    .statusCode(StatusCode.HEALTHY)
                    .ssn("12345612345123")
                    .name("BabyMonster")
                    .age(3)
                    .height(170)
                    .weight(73)
                    .build();
}

@Test
@DisplayName("Monster Created Test")
void createMonster() throws Exception {
    given(mMakerService.createMonster(getCreateRequest()))
            .willReturn(CreateMonsterDto.TestResponse.fromEntity(defaultMonster));
    
    CreateMonsterDto.Response result = mMakerService.createMonster(getCreateRequest());
    
    mockMvc.perform(
                    post("/create-monster")
                            .contentType(contentType)
                            .content(new ObjectMapper().writeValueAsString(result)))
            .andExpect(status().isOk())
            .andDo(print())
            .andReturn();
    then(mMakerService).should(times(2)).createMonster(getCreateRequest());
}

given(mMakerService.createMonster(getCreateRequest())) and

CreateMonsterDto.Response result = mMakerService.createMonster(getCreateRequest());

All of them are returning the same null value.

The solution to this problem was to add @EqualsAndHashCode Annotation to DtoRequest.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@EqualsAndHashCode(of = "id")
public static class Request {

    @NotNull
    private Long id;

    @NotNull
    private MonsterLevel monsterLevel;

    @NotNull
    private MonsterType monsterType;

    @NotNull
    private StatusCode statusCode;

    @NotNull
    @Size(min = 13, max = 15, message = "ssn max_size 14")
    private String ssn;

    @NotNull
    @Size(min = 3, max = 100, message = "name size must 3~100")
    private String name;

    @NotNull
    @Min(0)
    @Max(100)
    private Integer age;

    @NotNull
    @Min(150)
    @Max(300)
    private Integer height;

    @NotNull
    @Min(50)
    @Max(500)
    private Integer weight;
}

mMakerService.createMonster(getCreateRequest()); Is it a problem by taking out the address reference value, not the content, from the ?

Below is the code of the service stage.

public CreateMonsterDto.Response createMonster(
            CreateMonsterDto.Request request
    ) {
    validateCreateMonsterRequest(request);

    return CreateMonsterDto.Response.fromEntity(
            monsterRepository.save(
                    createMonsterFromRequest(request)
            )
    );
}

private MonsterEntity createMonsterFromRequest(CreateMonsterDto.Request request) {
   return MonsterEntity.builder()
        .id(1L)
        .monsterLevel(request.getMonsterLevel())
        .monsterType(request.getMonsterType())
        .statusCode(request.getStatusCode())
        .ssn(request.getSsn())
        .name(request.getName())
        .age(request.getAge())
        .height(request.getHeight())
        .weight(request.getWeight())
        .build();
}

When I ran this process in ServiceTest, there was no problem.

I would like to know the cause of this problem. Help. Sorry for the poor question. I'm using a translator.

I'm looking for a problem while debugging, but when I debug in ControllerTest, I can't debug until the service stage...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一页 2025-02-13 03:34:40

given(mMakerService.createMonster(getCreateRequest()))
    .willReturn(CreateMonsterDto.TestResponse.fromEntity(defaultMonster));

您告诉模拟框架时,当调用getCreaterequest()作为参数的请求时,将默认怪物从模拟的mmakerservice返回默认怪物。

然后,您在测试中调用模拟的MMAKERSERVICE,将另一个呼叫的结果访问getCreaterequest()。结果是无效的,因为两个调用getCreaterequest()将返回请求的两个单独实例。如果不正确实施equals(),这两个请求将被视为非平等,因为它们是不同的实例,因此具有不同的参考。通过在请求类中添加@equalsandhashcode,您确保两个实例现在被认为是平等的。

您的代码还有另一个问题。在测试中调用模拟(见上文)没有任何意义。您告诉模拟返回特定的默认怪物。调用模拟只会返回您在上面说的一行。您可以通过将DefaultMonster作为Result来实现。

With

given(mMakerService.createMonster(getCreateRequest()))
    .willReturn(CreateMonsterDto.TestResponse.fromEntity(defaultMonster));

you tell the mocking framework to return the default monster from the mocked mMakerService when it is called with the request returned from getCreateRequest() as parameter.

Then you call the mocked mMakerService inside your test passing the result of another call to getCreateRequest(). The result is null because the two calls to getCreateRequest() will return two separate instances of the request. Without a proper implementation of equals() the two requests will be regarded as non-equal, because they are different instances and have therefore different references. By adding @EqualsAndHashCode to the request class you have made sure that the two instances are now regarded as equal.

There is another problem with your code. Calling the mock inside your test (see above) is not making any sense. You told the mock to return a specific default monster. Calling the mock will just return what you told it one line above. You could have achieved the same by using defaultMonster as the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文