【问题标题】:Spring Boot @RestRepositoryResouce: Patching boolean property isn't workingSpring Boot @RestRepositoryResouce:修补布尔属性不起作用
【发布时间】:2019-05-30 17:06:32
【问题描述】:

我有一个简单的模型类:

@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());
}

编辑:修改后的测试方法要明确。

【问题讨论】:

  • 我猜你正在将完成设置为任务1,而不是更新任务。
  • 我正在从存储库中提取“更新”记录。

标签: java rest spring-boot patch spring-data-rest


【解决方案1】:

终于想通了。结果发现我的模型类中的 getter 和 setter 命名不正确。

他们应该是:

    public boolean getIsCompleted() {
    return isCompleted;
}

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

根据此 SO Post 找到答案: JSON Post request for boolean field sends false by default

【讨论】:

    猜你喜欢
    • 2011-11-29
    • 2018-12-18
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2018-08-28
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多