【发布时间】:2017-09-25 07:10:21
【问题描述】:
我正在尝试使用 Spring Boot Test 进行简单的集成测试,以测试 e2e 用例。我的测试不起作用,因为我无法让存储库保存数据,我认为我的 spring 上下文有问题...
这是我的实体:
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Person {
@Id
private int id;
private String name;
}
这是个人存储库:
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
个人服务:
@Service
public class PersonService {
@Autowired
private PersonRepository repository;
public Person createPerson(int id,String name) {
return repository.save(new Person(id, name));
}
public List<Person> getPersons() {
return repository.findAll();
}
}
个人控制器:
@RequestMapping
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping("/persons")
public List<Person> getPersons() {
return personService.getPersons();
}
}
主要应用类:
@SpringBootApplication
public class BootIntegrationTestApplication {
public static void main(String[] args) {
SpringApplication.run(BootIntegrationTestApplication.class, args);
}
}
application.properties 文件:
spring.datasource.url= jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
还有测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BootIntegrationTestApplicationTests {
@Autowired
private PersonService personService;
@Autowired
private TestRestTemplate restTemplate;
@Test
@Transactional
public void contextLoads() {
Person person = personService.createPerson(1, "person1");
Assert.assertNotNull(person);
ResponseEntity<Person[]> persons = restTemplate.getForEntity("/persons", Person[].class);
}
}
测试不起作用,因为服务没有保存 Person 实体 .... 在此先感谢
【问题讨论】:
-
当然不是...您的测试是事务性的,因此事务包装了您的测试方法。所以它是之后回滚(并且您的服务参与该事务)。即使你会
flush它也不会工作,因为你正在使用 rest 来访问将打开一个新事务的应用程序。完成这项工作的唯一方法是使测试不是事务性的。 -
您可以尝试拆分测试。创建私有方法保存带有事务注释的人并从测试方法中调用它。
-
正如@M.Deinum 所说,事务在您的测试中回滚,您看不到任何变化。尝试将 '@Commit' 或 @Rollback(false) 添加到您的测试中。
-
这也行不通,因为涉及 2 个事务,并且第一个事务在他调用其余服务之前尚未提交。后者将启动另一个事务,但由于另一个事务仍未提交,因此它看不到该数据(记住 ACID 中的 I 用于隔离)
标签: java spring spring-boot spring-test