使用邮递员返回了错误的请求,但未在单元测试的春季启动中返回

问题描述

我有一个具有唯一字段“名称”的类别实体。

我正在使用一个自定义的唯一批注来验证数据,它可以完美运行。

我正在尝试在我的spring boot应用程序上测试我的控制器,我想检查如果数据重复(唯一名称),请求是否返回400状态。

在邮递员中,它按预期工作,并返回400状态和错误列表。

在进行单元测试时,它返回201状态,其中包含一个空的主体(但实际上,返回201表示该主体包含新创建的实体!)

这是我的测试

    @Test
    public void testIfAdminCanCreateCategory_expect400BecauseCategoryAlreadyExist() throws Exception {
        // json
        String data = "{\"name\" : \"CATEGORY\"}";
        mockMvc().with(keycloakAuthenticationToken().authorities("ROLE_admin")).perform(post("/categories").content(data).contentType("application/json"))
                .andDo(print())
                .andDo(r -> mockMvc().with(keycloakAuthenticationToken().authorities("ROLE_admin"))
                        .perform(post("/categories").content(data).contentType("application/json"))
                        .andExpect(status().isBadRequest()));
    }

我的控制器:

    @PostMapping
    @PreAuthorize("hasRole('ROLE_admin')")
    public HttpEntity<MainCategory> create(@Valid @RequestBody CreateMainCategory createMainCategory)
    {
        return ResponseEntity.status(HttpStatus.CREATED).body(mainCategoryService.create(createMainCategory));
    }

我的服务:

    @Override
    public MainCategory create(CreateMainCategory createMainCategory) {
        MainCategory mainCategory = new MainCategory();
        mainCategory.setName(createMainCategory.getName().toUpperCase());
        return mainCategoryRepository.save(mainCategory);
    }

我的实体:

@Entity
@EntityListeners( AuditingEntityListener.class  )
@Data
public class MainCategory {

    @Id @GeneratedValue private Long id;

    private String name;

    @CreatedBy
    private String createdBy;

    @OneToMany(cascade = CascadeType.REMOVE,mappedBy = "mainCategory")
    List<Category> categories;
}

日志请求:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /categories
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8",Content-Length:"21"]
             Body = {"name" : "CATEGORY"}
    Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@6989924: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@6989924: Principal: user; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@40fd518f; Granted Authorities: ROLE_admin}

日志响应:

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Vary:"Origin","Access-Control-Request-Method","Access-Control-Request-Headers",X-Content-Type-Options:"nosniff",X-XSS-Protection:"1; mode=block",Cache-Control:"no-cache,no-store,max-age=0,must-revalidate",Pragma:"no-cache",Expires:"0",X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :400
Actual   :201

解决方法

问题与save()方法有关,即使在我的属性文件中定义mysql数据库时,也没有保存任何实体(这解释了201创建状态下的空主体)。

一种解决方案是使用H2数据库进行测试,将其配置添加到单独的属性文件中(在我的情况下为product-service-test.yml),然后将@ActiveProfiles("test") 添加到测试类中。

,

在测试案例中,无处显示数据重复。您正在测试用例中定义String数据并在其中使用它。因此,它给出了200个已创建状态。

在实体创建中,名称未定义为唯一。

@Column(unique=true)
private String name;

默认情况下为假。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...