繁体   English   中英

Spring Boot @RestRepositoryResouce:修补布尔属性不起作用

[英]Spring Boot @RestRepositoryResouce: Patching boolean property isn't working

我有一个简单的模型类:

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

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

终于想通了。 原来我的模型类中的getter和setter被错误地命名了。

他们应该是:

    public boolean getIsCompleted() {
    return isCompleted;
}

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

根据此SO Post找到答案: 默认情况下,布尔字段的JSON Post请求发送false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM