英文:
Java Spring Boot Unit Test Service State not Refreshing for each Unit Test
问题
我是Java Spring Boot的新手。请问有人知道为什么我的 service 在每次单元测试之前都不会刷新状态吗?
我已经试了整整一天,甚至更长时间,但还是找不出原因。我以为 @BeforeEach 会在每个单元测试之前再次刷新服务,但这并不起作用。
test1 改变了 service 的状态并通过了断言,但 service 的状态被带入了 test2,这就是问题所在。因此 test2 失败了。
非常感谢任何帮助!
class BeachResortServiceApplicationTests {
private PersonDataAccessService service;
@BeforeEach
void init() {
service = new PersonDataAccessService();
}
@Test
void test1() {
System.out.println("Test1");
UUID id = UUID.randomUUID();
Person bob = new Person(id, "Bob");
service.insertPerson(bob);
assert(service.getPersonById(id).equals(bob));
}
@Test
void test2() {
System.out.println("Test2");
System.out.println(service.getAllPersons());
// 这个断言失败了,因为服务仍然包含Bob,但根据 @BeforeEach 方法,服务应该已经被清除。
assertThat(service.getAllPersons()).hasSize(0);
}
}
英文:
I am new to Java Spring Boot. Please does anyone know why my service's state is not refreshing before each unit test?
I've been trying to fix this for a whole day if not more and am yet to find out why. I thought the @BeforeEach would refresh the service again before each unit test, but this is not working.
test1 changes the state of service and passes the assertion but the state of service is carried into test2, which is the issue. This therefore makes test2 fail
Any help is greatly appreciated!
class BeachResortServiceApplicationTests {
private PersonDataAccessService service;
@BeforeEach
void init() {
service = new PersonDataAccessService();
}
@Test
void test1() {
System.out.println("Test1");
UUID id = UUID.randomUUID();
Person bob = new Person(id, "Bob");
service.insertPerson(bob);
assert(service.getPersonById(id).equals(bob));
}
@Test
void test2() {
System.out.println("Test2");
System.out.println(service.getAllPersons());
//this assertion fails because service still has Bob in it but service should have been cleared
//according to the @BeforeEach method.
assertThat(service.getAllPersons()).hasSize(0);
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论