我在所有集成测试中不断收到异常,而单元测试运行良好。所有异常如下所示:
UsersControllerTest > getOneUser() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException at ScriptUtils.java:626
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException at DbException.java:459
我正在使用木星进行测试。我认为上述例外指向我必须填充一些数据的 data.sql 脚本。对我来说,就语法而言似乎没问题,而且运行良好,这意味着如果用邮递员测试会生成记录:
INSERT INTO AUTHORITY (ID_AUTHORITY,AUTHORITY) VALUES (1,'USER');
INSERT INTO AUTHORITY (ID_AUTHORITY,AUTHORITY) VALUES (2,'MODERATOR');
INSERT INTO AUTHORITY (ID_AUTHORITY,AUTHORITY) VALUES (3,'ADMIN');
INSERT INTO USER (USER_ID,FIRST_NAME,LAST_NAME,ID,PASSWORD,EMAIL,EMAIL_VERIFIED,ACCOUNT_NON_EXPIRED,ACCOUNT_NON_LOCKED,ENABLED,CREDENTIALS_NON_EXPIRED)
VALUES (1,'Alisher','Urunov','b006c568-a79b-4c28-a06c-df7d89579e00','$2y$12$vLPHTGSDyNWBdH.zxuJgfeiExUwh3zT3Cgj8ZZzW.38rDNK/yBJtm','urunov.alisher@some.com',TRUE,TRUE,TRUE,TRUE,TRUE);
INSERT INTO USER (USER_ID,FIRST_NAME,LAST_NAME,ID,PASSWORD,EMAIL,EMAIL_VERIFIED,ACCOUNT_NON_EXPIRED,ACCOUNT_NON_LOCKED,ENABLED,CREDENTIALS_NON_EXPIRED)
VALUES (2,'Ralf','Tester','b006c568-a79b-123s-a06c-df7d89579e00','$2a$10$3D8eyR7FouUb3RjKoVd9r.pBa7wZbOCe4BeIgxJmJmT9kbYGU43qC','ralf@gmail.com',FALSE,TRUE,TRUE,TRUE,TRUE);
INSERT INTO USER (USER_ID,FIRST_NAME,LAST_NAME,ID,PASSWORD,EMAIL,EMAIL_VERIFIED,ACCOUNT_NON_EXPIRED,ACCOUNT_NON_LOCKED,ENABLED,CREDENTIALS_NON_EXPIRED)
VALUES (3,'Ronald','The Great','b006c568-a79b-123s-1248-df7d89579e00','$2a$10$l9jefOjW/P0/dYH.MkHO8OJkNc7SN/G4ZOK1Lk9ND0x08Yta9hJrq','roland.theGreat@gmail.com',TRUE,TRUE,TRUE,TRUE,TRUE);
INSERT INTO USER_AUTHORITY (ID_USER,ID_AUTHORITY) VALUES (1,1);
INSERT INTO USER_AUTHORITY (ID_USER,ID_AUTHORITY) VALUES (1,2);
INSERT INTO USER_AUTHORITY (ID_USER,ID_AUTHORITY) VALUES (1,3);
INSERT INTO USER_AUTHORITY (ID_USER,ID_AUTHORITY) VALUES (3,1);
也想到了 Spring boot 可能存在的配置问题,所以在 gradle.build 中添加了 jdbc starter 依赖,但是好像还是失败了。
这是测试的一部分:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = UserServiceApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = UserServiceApplication.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class UsersControllerTest {
private String adminToken;
private String userToken;
@Autowired TestRestTemplate restTemplate;
@Autowired TokenUtils tokenUtils;
@BeforeEach
void setUp() {
userToken = tokenUtils.generateTokenForUser(user());
adminToken = tokenUtils.generateTokenForUser(admin());
}
@Test
void getOneUser() {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer "+adminToken);
headers.add("Access-Control-Expose-Headers", "Authorization");
ResponseEntity<UserModel> result =
restTemplate.exchange(
"/users/userInfo", HttpMethod.GET, new HttpEntity<>(headers), UserModel.class);
assertEquals("awesome@gmail.com", result.getBody().getEmail());
}