首页 > 解决方案 > Spring Boot @RestRepositoryResouce:修补布尔属性不起作用

问题描述

我有一个简单的模型类:

@Entity
public class Task {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Size(min = 1, max = 80)
  @NotNull
  private String text;

  @NotNull
  private boolean isCompleted;

这是我的 Spring Rest 数据存储库:

@CrossOrigin // TODO: configure specific domains
@RepositoryRestResource(collectionResourceRel = "task", path 
= "task")
public interface TaskRepository extends CrudRepository<Task, 
Long> {

}

因此,作为健全性检查,我正在创建一些测试来验证自动创建的端点。发布、删除和获取工作正常。但是,我无法正确更新 isCompleted 属性。

这是我的测试方法。第一个通过没有问题,但第二个失败。

    @Test
    void testUpdateTaskText() throws Exception {
      Task task1 = new Task("task1");
      taskRepository.save(task1);

      // update task text and hit update end point
      task1.setText("updatedText");
      String json = gson.toJson(task1);
      this.mvc.perform(patch("/task/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(json))
            .andExpect(status().isNoContent());

      // Pull the task from the repository and verify text="updatedText"
      Task updatedTask = taskRepository.findById((long) 1).get();
      assertEquals("updatedText", updatedTask.getText());
}

    @Test
    void testUpdateTaskCompleted() throws Exception {
      Task task1 = new Task("task1");
      task1.setCompleted(false);
      taskRepository.save(task1);

      // ensure repository properly stores isCompleted = false
      Task updatedTask = taskRepository.findById((long) 1).get();
      assertFalse(updatedTask.isCompleted());

      //Update isCompleted = true and hit update end point
      task1.setCompleted(true);
      String json = gson.toJson(task1);
      this.mvc.perform(patch("/task/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(json))
            .andExpect(status().isNoContent());

      // Pull the task from the repository and verify isCompleted=true
      updatedTask = taskRepository.findById((long) 1).get();
      assertTrue(updatedTask.isCompleted());
}

编辑:修改后的测试方法要清楚。

标签: javarestspring-bootpatchspring-data-rest

解决方案


终于想通了。原来我的模型类中的 getter 和 setter 命名不正确。

他们应该是:

    public boolean getIsCompleted() {
    return isCompleted;
}

    public void setIsCompleted(boolean isCompleted) {
    this.isCompleted = isCompleted;
}

根据此 SO Post 找到答案: JSON Post request for boolean field 默认发送 false


推荐阅读