java - 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());
}
编辑:修改后的测试方法要清楚。
解决方案
终于想通了。原来我的模型类中的 getter 和 setter 命名不正确。
他们应该是:
public boolean getIsCompleted() {
return isCompleted;
}
public void setIsCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
根据此 SO Post 找到答案: JSON Post request for boolean field 默认发送 false
推荐阅读
- python - 使用聚合函数过滤输出
- powershell - 在 foreach 循环中第一次调用后,Jenkins 上的 Mstest 输出不需要的 UTF-8 字符
- php - PHP 脚本不等待 curl 响应
- mysql - 如何从文件中加载数据而不重复记录
- python - 没有属性'get_default_graph'
- windows - 尝试在 Windows 7 机器上使用批处理文件自动化简单的任务和过程控制
- python - 在 Python 单元测试中分别模拟多个 API 请求
- android - 从 SMS REACT NATIVE 中读取消息
- power-automate - 为什么我的流(用于 SharePoint 列表)针对我列表中的所有项目运行?
- excel - 复制 Sheet1 范围在 Sheet2 上向下粘贴八行