我的应用程序REST控制器在单元测试和正常运行之间遇到了不同的行为。我在我的一个字段上添加了一个@Column(unique = true)来约束一个唯一的数字,不知怎的,它在单元测试中被忽略了,我无法理解为什么。我在下面展示了一个简短的例子,基本上将两辆车的数量相同的车辆添加到商店:
@Test
public void CreateVehicle_SameNR_NOK() {
Shop shop = shopController.createVehicle(0L,1,new Vehicle("AAA",
"111222"));
Assert.assertEquals(shop.getVehicles().size(),1);
shopController.createVehicle(0L,1,new Vehicle("AAA",
"111222"));
Assert.assertEquals(shop.getVehicles().size(),1); //This fails.
}
@Entity
public class Vehicle {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@NotNull
private String name;
@NotNull
@Column(unique = true) //ignored in unit test?
private String nr;
protected Vehicle() {}
public Vehicle(String name, String nr) {
this.name = name;
this.nr = nr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNr() {
return nr;
}
public void setNr(String nr) {
this.nr = nr;
}
}
spring.datasource.url=jdbc:h2:mem:test_mem;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
logging.level.org.springframework.web=DEBUG
debug=true
@RequestMapping(value ="{id}/shop/{shopId}/vehicle", method = RequestMethod.POST)
public Shop createShopVehicle(@PathVariable Long id, @PathVariable Long shopId, @RequestBody Vehicle vehicle) {
Shop shop = shopRepository.findOne(shopId);
shop.getVehicles().add(vehicle);
shopRepository.save(shop);
return shop;
}