2017-08-03 51 views
0

我们正在将Apache CXF资源迁移到Spring MVC。它发生了,我们更好地将资源迁移到服务,并为所有人提供一个大的控制器。在这里我们收到:将MockBean移到单独的配置对象中

@Component 
public class MainResource { 
    ... 
    @Path("/first") 
    public FirstResource getFirstResource() { 
    ... 
    @Path("/second") 
    public SecondResource getSecondResource() { 

@Component 
public class FirstResource { 
    @GET 
    @Path("/") 
    public FirstEntity getFirstEntity() { 

@Component 
public class SecondResource { 
    @GET 
    @Path("/") 
    public SecondEntity getSecondEntity() { 

在这里,我们现在有:

@Controller 
public class MainController { 
    @Resource 
    FirstService firstService; 
    @Resource 
    SecondService secondService; 
    ... 
    @GetMapping(/first) 
    public FirstEntity getFirst() { 
    ... 
    @GetMapping(/second) 
    public SecondEntity getSecond() { 

但是,当它来测试控制器的以下问题出现了:我们要在每一个分割每个服务测试,以便测试我们必须为每个服务使用@MockBean(否则它无法启动应用程序上下文)。所以这里是问题:

@RunWith(SpringRunner.class) 
@WebMvcTest(MainController.class) 
public class FirstWebMvcTest { 
    @MockBean 
    FirstService firstService; 
    @MockBean 
    SecondService secondService; 

    // testing /first call only. secondService is not used 

@RunWith(SpringRunner.class) 
@WebMvcTest(MainController.class) 
public class SecondWebMvcTest { 
    @MockBean 
    FirstService firstService; 
    @MockBean 
    SecondService secondService; 

    // testing /second call only. firstService is not used 

我们不想复制@MockBean。作为一个临时解决方案,我已经把他们全部都转到了基础类。但我不喜欢扩展基础测试类来获得这个定义,在我看来,这似乎是一个肮脏的解决方案。理想情况下,我想将它移动到某个配置或其他位置。

感谢您的任何建议!

回答

1

您可以在测试src中创建一个@Configuration类。

@Configuration 
@MockBean(FirstService.class) 
public class foo{ 

} 

并在需要时将其导入,或如果组分扫描添加@Profile它,因此它会活跃当某一简档是活动的,用于测试和使用模拟豆。

+1

嗯,但它不会在测试中注入模拟.. –