ltf*_*hie 6 jta spring-test atomikos maven spring-boot
我正在使用spring-boot 1.4.3中引入的测试注释进行集成测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceIT { }
Run Code Online (Sandbox Code Playgroud)
根据文档,测试上下文将被缓存并重新使用以加速集成测试。我想要这种行为,因为初始化应用程序上下文需要花费大量时间。我的故障安全插件配置有
<forkCount>1</forkCount>
<reuseForks>true</reuseForks>
Run Code Online (Sandbox Code Playgroud)
允许集成测试在同一过程中运行,以利用应用程序上下文缓存。
最近,我写了一个集成测试,使用@MockBean批注来模拟某些bean的行为。
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnotherServiceIT {
@MockBean
SomeService service1
}
Run Code Online (Sandbox Code Playgroud)
尽管测试本身运行良好,但通过maven验证运行时,多个集成测试失败并显示错误消息
javax.naming.NamingException:名称为dataSource的另一资源已存在-选择其他名称
如果我跳过带有JUnit @Ignore批注的特定测试,一切将恢复正常。
此行为似乎表明使用@MockBean会更改缓存行为,并且每个测试都尝试创建自己的数据源。我还应该提到我正在使用通过XADataSourceAutoConfiguration创建的AtomikosDataSourceBean。
如何克服此问题,以便集成测试仍可以使用缓存的上下文并同时使用@MockBean
?
Hmm, does SomeService relate to your Datasource in any way?
Because your context is cached and @MockBean does the following:
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,
and
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;
Run Code Online (Sandbox Code Playgroud)
Edit:
So if your SomeService is an implementation of a DataSource try adding a Qualifier. If SomeService has a DataSource in it, and you need to access some methods in it, you could try to use @Mock and specify the any objects that need to be returned either through their own mock or 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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1023 次 |
最近记录: |