@DataJpaTest 注解测试提示错误 Wrong user name or password

提示的错误信息如下:

Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-200]
	at org.h2.message.DbException.getJdbcSQLException(DbException.java:461)
	at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
	at org.h2.message.DbException.get(DbException.java:205)
	at org.h2.message.DbException.get(DbException.java:181)
	at org.h2.message.DbException.get(DbException.java:170)
	at org.h2.engine.Engine.validateUserAndPassword(Engine.java:357)
	at org.h2.engine.Engine.createSessionAndValidate(Engine.java:176)
	at org.h2.engine.Engine.createSession(Engine.java:166)
	at org.h2.engine.Engine.createSession(Engine.java:29)
	at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340)
	at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173)
	at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152)
	at org.h2.Driver.connect(Driver.java:69)
	at org.springframework.jdbc.datasource.SimpleDriverDataSource.getConnectionFromDriver(SimpleDriverDataSource.java:144)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:179)
	at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy.getConnection(EmbeddedDatabaseFactory.java:263)
	at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
	at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)

在默认情况下 DataJpaTest 测试将会使用 H2 数据库载入内存后进行测试。

如果你的配置不正确将会提示用户名和密码错误。

所以我们可以选择 DataJpaTest 不载入 H2 进行测试。

问题和解决

解决办法是添加下面这句话:

@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)

在测试类中,添加上上面这句话将会告诉 Spring Boot 的测试从 application.properties 文件中载入数据库配置信息。

上面的意思是不使用 H2 数据库,而使用 Spring Boot 的配置数据源。

最好的办法就是使用 @SpringBootTest 来进行测试。