Tôi mới làm quen với khung công tác Spring. Tôi cần phải viết bài kiểm tra đơn vị cho kho lưu trữ JPA. Tôi đang thử phương thức kho đơn giản saveAndFlush()
. Nhưng không có gì lưu trong kho của tôi. Đây là mã nguồn của tôi:Đơn vị mùa xuân kiểm tra kho lưu trữ JPA
TestContext.class
@Configuration
@PropertySource("classpath:log4j.properties")
public class TestContext {
@Bean
public RoleService roleService() {
return Mockito.mock(RoleService.class);
}
@Bean
public RightService RightService() {
return Mockito.mock(RightService.class);
}
@Bean
public RoleRepository RoleRepository() {
return Mockito.mock(RoleRepository.class);
}
}
RoleServiceTest.class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class})
@WebAppConfiguration
public class RoleServiceTest {
@Autowired
private RoleRepository roleRepository;
@Test
public void TestServices() throws Exception {
RoleDetails first = new RoleDetails();
first.setId("1");
first.setDescription("First Description");
first.setName("First");
roleRepository.saveAndFlush(new RoleEntity(first));
roleRepository.save(new RoleEntity(first));
List<RoleEntity> roles = new ArrayList<RoleEntity>();
roles = roleRepository.findAll();
System.out.println(roles);
assertEquals(1, roles.size());
}
}
Và lỗi:
java.lang.AssertionError: expected:<1> but was:<0>
Tôi gần như chắc chắn có vấn đề xảy ra vì testContext.Class. Tôi đã sử dụng lớp này để kiểm tra bộ điều khiển của tôi và nó hoạt động tốt, nhưng bây giờ tôi cần phải kiểm tra cơ sở dữ liệu của tôi và tôi không biết làm thế nào để sửa đổi contextConfiguration. Tôi hy vọng ai đó sẽ giúp tôi. Cảm ơn trước!
này là chính xác về mặt kỹ thuật, nhưng rất nhiều mùa xuân kho dữ liệu sử dụng logic tự động triển khai cho các hoạt động CRUD cơ bản. Cố gắng để khởi tạo chúng trực tiếp sẽ không hoạt động; bạn nên hiển thị cách thay thế chúng bằng '@ Autowired' hoặc' @ Resource'. –