我有一个问题: 仅加载我想在该集成测试中测试的 Enpoint 类而不是完整的应用程序上下文(不是所有 Enpoint 类(的正确配置是什么? 现在我有:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebServiceConfigTest.class}, properties = {"application.address=http://hostname:port/context"})
public class MyEndpointTest {
@Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
@Before
public void init() {
mockClient = MockWebServiceClient.createClient(applicationContext);
MockitoAnnotations.initMocks(this);
}
@Test
public void test1(){}
....
}
在WebServiceConfigTest中是:
@ComponentScan("mypackages.soap")
@ContextConfiguration(classes = SoapApplication.class)
@MockBean(classes = {MyService.class})
public class WebServiceConfigTest {
}
肥皂应用是:
@ComponentScan({"mypackages"})
@SpringBootApplication
public class SoapApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(SoapApplication.class, args);
}
}
原因是在 Soap 模块中,我有一个服务模块的依赖项,该模块还有其他依赖项等等。 如果我加载整个应用程序上下文,那么:
- 要么我需要模拟我在 Soap 模块中使用的服务的完整列表
- 或者模拟服务模块的底层依赖关系,如数据源、队列等。
如果我这样做第二个将使 Soap 模块意识到它不应该的事情。 如果我做第一个,我被迫在配置测试文件中模拟和维护可能很长的已用服务的完整列表。
这里有什么建议吗?
仅加载我要在该集成测试中测试的端点类而不是完整的应用程序上下文的正确配置是什么
你可以要求 Spring 只实例化特定的Controller
类,而不加载完整的应用程序上下文,使用 @WebMvcTest(MyEndpoint.class(
@RunWith(SpringRunner.class)
@WebMvcTest(MyEndpoint.class)
public class MyEndpointTest {
@MockBean //mock all service beans that are injected into controller
private Service service;
@Autowired
private MockMvc mockMvc;
@Test
public void test1(){}
....
}
}
如果您使用的是嵌入式数据库(例如 H2(或用于测试的嵌入式队列,我还建议您使用@SpringBootTest
进行端到端集成测试
经过长时间的搜索和试验,我找到了解决方案。 正如你可以要求 Spring on REST 只将 1 个控制器放入上下文中
一样@WebMvcTest(MyController.class)
你可以为肥皂做的同样的事情
@SpringBootTest(classes = {MyEndpoint.class})
它将只加载你想要的端点,你可以模拟你在里面使用的服务,或者你可以一直到存储库,无论你的应用程序业务逻辑在那里做什么。