我正在测试一个Spring Boot应用程序。我有几个测试类,每个类都需要一组不同的模拟bean或定制bean。
以下是设置的草图:
src/main/java:
package com.example.myapp;
@SpringBootApplication
@ComponentScan(
basePackageClasses = {
MyApplication.class,
ImportantConfigurationFromSomeLibrary.class,
ImportantConfigurationFromAnotherLibrary.class})
@EnableFeignClients
@EnableHystrix
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
package com.example.myapp.feature1;
@Component
public class Component1 {
@Autowired
ServiceClient serviceClient;
@Autowired
SpringDataJpaRepository dbRepository;
@Autowired
ThingFromSomeLibrary importantThingIDontWantToExplicitlyConstructInTests;
// methods I want to test...
}
src/test/java:
package com.example.myapp;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class Component1TestWithFakeCommunication {
@Autowired
Component1 component1; // <-- the thing we're testing. wants the above mock implementations of beans wired into it.
@Autowired
ServiceClient mockedServiceClient;
@Configuration
static class ContextConfiguration {
@Bean
@Primary
public ServiceClient mockedServiceClient() {
return mock(ServiceClient.class);
}
}
@Before
public void setup() {
reset(mockedServiceClient);
}
@Test
public void shouldBehaveACertainWay() {
// customize mock, call component methods, assert results...
}
}
package com.example.myapp;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class Component1TestWithRealCommunication {
@Autowired
Component1 component1; // <-- the thing we're testing. wants the real implementations in this test.
@Autowired
ServiceClient mockedServiceClient;
@Before
public void setup() {
reset(mockedServiceClient);
}
@Test
public void shouldBehaveACertainWay() {
// call component methods, assert results...
}
}
上面设置的问题是,在MyApplication中配置的组件扫描会拾取Component1TestWithFakeCommunication.ContextConfiguration,,所以即使在Component1TestWithRealCommunication中我也会得到一个模拟的ServiceClient,而我想要的是真正的ServiceClient实现。
虽然我可以在两个测试中使用@Autowired构造函数并自己构建组件,但有足够数量的复杂设置的东西我宁愿让Spring为我设置(例如,Spring Data TestContext存储库,来自应用程序外部的库的组件,从Spring上下文中提取bean,等等)。在可以本地覆盖Spring上下文中的特定bean定义的测试中嵌套Spring配置,感觉应该是一种干净的方法;唯一的缺点是,这些嵌套的配置最终会影响所有基于MyApplication (组件扫描应用程序包)的Spring TestContext测试。
我如何修改我的设置,使我在每个测试类中只有几个本地覆盖的bean,仍然为我的测试获得一个“大部分真实的”Spring上下文?
发布于 2018-06-17 00:48:24
如果你有一个@SpringBootTest
,你可以用@MockBean
注释你想要模拟的服务。就这么简单。
https://stackoverflow.com/questions/39300167
复制相似问题