日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

junit跳过datasource_maven – spring集成测试无法加载上下文“另一个资源已存在,名称为dataSource”...

發(fā)布時間:2024/7/5 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 junit跳过datasource_maven – spring集成测试无法加载上下文“另一个资源已存在,名称为dataSource”... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我正在使用

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。