junit跳过datasource_maven – spring集成测试无法加载上下文“另一个资源已存在,名称为dataSource”...
我正在使用
spring-boot 1.4.3中引入的測試注釋進行集成測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceIT { }
根據(jù)documentation,測試上下文被緩存并重用以加速集成測試.這種行為是我想要的,因為它需要大量的時間來初始化應用程序上下文.我的故障安全插件配置了
1
true
允許集成測試在同一進程中運行,以利用應用程序上下文緩存.
最近,我編寫了一個使用@MockBean注釋的集成測試來模擬某些bean的行為.
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnotherServiceIT {
@MockBean
SomeService service1
}
雖然測試運行良好,但是當通過maven驗證運行時,多個集成測試會因錯誤消息而失敗
javax.naming.NamingException: Another resource already exists with
name dataSource – pick a different name
如果我使用JUnit @Ignore注釋跳過此特定測試,一切都恢復正常.
此行為似乎表明使用@MockBean更改了緩存行為,并且每個測試都嘗試創(chuàng)建自己的數(shù)據(jù)源.我還要提一下,我正在使用通過XADataSourceAutoConfiguration創(chuàng)建的AtomikosDataSourceBean.
如何克服此問題,以便我的集成測試仍然可以使用緩存上下文并同時使用@MockBean?
最佳答案 嗯,SomeService會以任何方式與您的數(shù)據(jù)源相關(guān)嗎?
因為您的上下文被緩存而@MockBean執(zhí)行以下操作:
used to add mocks to a Spring ApplicationContext … Any existing single bean of the same type defined in the context will be replaced by the mock,
和
If there is more than one bean of the requested type, qualifier metadata must be specified at field level:
@RunWith(SpringRunner.class)
public class ExampleTests {
@MockBean
@Qualifier("example")
private ExampleService service;
編輯:
因此,如果您的SomeService是DataSource的實現(xiàn),請嘗試添加限定符.如果SomeService中包含DataSource,并且您需要訪問其中的某些方法,則可以嘗試使用@Mock并指定需要通過自己的mock或autowire返回的任何對象.
@Mock
SomeService someService;
@Mock
SomeDependency mockDependency;
@Autowired
OtherDependency realDependency;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
doReturn(mockDependency).when(someService).getSomeDependency();
doReturn(realDependency).when(someService).getOtherDependency();
}
總結(jié)
以上是生活随笔為你收集整理的junit跳过datasource_maven – spring集成测试无法加载上下文“另一个资源已存在,名称为dataSource”...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle追踪触发器语句,Oracle
- 下一篇: 并行算法 Parallel Algori