在 H2 JPA 测试中更新 @Id(使用身份策略)
Update @Id (using identity strategy) in H2 JPA test
我有一个检查最后插入的 id 的测试我正在使用 H2 进行测试
@Entity
@Data
public class Guy implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
protected Long id;
@Column(nullable = false)
protected String name;
}
这是测试
@Test
public void getTest() {
String jsonResponse = "{\"name\":\"andrew\"}";
Response response = given().body(jsonResponse).header("Content-Type",
"application/json").header("Client", 123).post("/thin/guy");
assertEquals(HttpServletResponse.SC_CREATED,response.getStatusCode());
//here the record was created
JSONObject jsonObject = new JSONObject(response.getBody().print());
Response resGet = given().header("Client",123).get("/thin/guy/"+String.valueOf(jsonObject.get("id")));
assertEquals(HttpServletResponse.SC_OK, resGet.getStatusCode());
//this is the response "{\"id\":1,\"name\":\"andrew\"}"
JSONObject getGuy = new JSONObject(resGet.getBody().print());
assertEquals(5000L,Long.valueOf(getGuy.get("id").toString()));
}
我如何制作仅在测试范围内运行的 H2 数据库,returns 插入的 id 具有 de 值,例如 5000。
有没有可能在测试范围内给实体Guy设置star值?谢谢!
不检查新创建对象的 ID 的实际值。
- 没有理由检查id。 id 由数据库引擎生成,但您在测试期间使用不同的引擎,因此您的测试用例将测试您的测试环境的行为...
- 测试可以 运行 随机排序,因此当您添加更多测试或更改测试数据时,您的旧测试将开始失败。
如果您真的想测试某些东西,请测试新创建对象的属性(如 XtremeBaumer 建议的那样)。
或者您可以测试创建时返回的对象是否与GET请求时返回的对象完全相同。
assertEquals(jsonObject, testGuy);
我有一个检查最后插入的 id 的测试我正在使用 H2 进行测试
@Entity
@Data
public class Guy implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
protected Long id;
@Column(nullable = false)
protected String name;
}
这是测试
@Test
public void getTest() {
String jsonResponse = "{\"name\":\"andrew\"}";
Response response = given().body(jsonResponse).header("Content-Type",
"application/json").header("Client", 123).post("/thin/guy");
assertEquals(HttpServletResponse.SC_CREATED,response.getStatusCode());
//here the record was created
JSONObject jsonObject = new JSONObject(response.getBody().print());
Response resGet = given().header("Client",123).get("/thin/guy/"+String.valueOf(jsonObject.get("id")));
assertEquals(HttpServletResponse.SC_OK, resGet.getStatusCode());
//this is the response "{\"id\":1,\"name\":\"andrew\"}"
JSONObject getGuy = new JSONObject(resGet.getBody().print());
assertEquals(5000L,Long.valueOf(getGuy.get("id").toString()));
}
我如何制作仅在测试范围内运行的 H2 数据库,returns 插入的 id 具有 de 值,例如 5000。 有没有可能在测试范围内给实体Guy设置star值?谢谢!
不检查新创建对象的 ID 的实际值。
- 没有理由检查id。 id 由数据库引擎生成,但您在测试期间使用不同的引擎,因此您的测试用例将测试您的测试环境的行为...
- 测试可以 运行 随机排序,因此当您添加更多测试或更改测试数据时,您的旧测试将开始失败。
如果您真的想测试某些东西,请测试新创建对象的属性(如 XtremeBaumer 建议的那样)。 或者您可以测试创建时返回的对象是否与GET请求时返回的对象完全相同。
assertEquals(jsonObject, testGuy);