我有一个没有失败(但应该)的测试的 Spring Boot 项目。
我做错了什么还是Spring有问题?
对于一个小例子,我创建了一个包含 2 个实体(用户和类别)和一个具有 DELETE 方法(https://github.com/sk8ter/demo)的控制器类的小项目。
类别实体有一个没有级联选项的用户实体 id,因此在删除具有类别的用户时它应该会失败:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private long id;
private String name;
...
}
@Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
...
}
控制器也很简单:
@RestController
@RequestMapping(value = "/users", produces = "application/json;charset=UTF-8")
public class UserCategory {
@Autowired
private UserRepository userRepository;
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/{id}", method = DELETE, consumes = MediaType.ALL_VALUE)
public void deleteCategory(@PathVariable Long id) {
User user = userRepository.getOne(id);
userRepository.delete(user);
}
}
最后是一个测试:
@Transactional
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {
@Autowired
protected WebApplicationContext context;
protected MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testName() throws Exception {
mockMvc.perform(delete("/users/1"))
.andExpect(status().isOk());
// EntityManagerFactory entityManagerFactory = context.getBean(EntityManagerFactory.class);
// SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
// sessionFactory.getCurrentSession().flush();
}
}
如果我从DemoApplicationTests中删除@Transactional注释,测试将失败,但在这种情况下,更改将提交到数据库。
在测试中注释 3 行也无济于事。