报错信息:
2019-04-01 14:33:10.703 ERROR 1957 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@517a46f3] to prepare test instance [com.****.account.controller.CpsAccountLogControllerUnitTest@377e90b0]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cpsSettlementMapper' defined in URL [jar:file:/Users/pilaf/IdeaProject/hydra/hydra-dao/target/hydra-dao-0.0.1-SNAPSHOT.jar!/com/**/mapper/CpsSettlementMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
...
Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
at org.springframework.util.Assert.notNull(Assert.java:198)
...
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.626 s <<< FAILURE! - in com.****.account.controller.CpsAccountLogControllerUnitTest
[ERROR] testInsert(com.****.account.controller.CpsAccountLogControllerUnitTest) Time elapsed: 0.004 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cpsSettlementMapper' defined in URL [jar:file:/Users/pilaf/IdeaProject/hydra/hydra-dao/target/hydra-dao-0.0.1-SNAPSHOT.jar!/com/**/mapper/CpsSettlementMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
解决方式是在项目依赖中加入:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>1.3.2</version>
</dependency>
这个依赖信息在文章最后参考网址1中有说明。
然后在单元测试类上面加上
org.mybatis.spring.boot.test.autoconfigure.AutoConfigureMybatis
注解:
@ActiveProfiles("staging")
@RunWith(SpringRunner.class)
@AutoConfigureMybatis
@WebMvcTest(CpsAccountLogController.class)
public class CpsAccountLogControllerUnitTest {
....
}
参考网址:
1.http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-test-autoconfigure/
2.https://github.com/mybatis/spring-boot-starter/issues/227