【问题标题】:Springockito how to?Springockito 怎么用?
【发布时间】:2013-10-21 16:17:00
【问题描述】:

我想在我的一个 IT 中使用 Springockito 模拟 DAO bean。在我的 IT 中,我必须使用 spring context.xml 来自动装配一些服务,并使用 mockApplication.xml 来模拟 DAO。那么,如何同时使用两个xml配置文件呢?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {"classpath*:/MockApplicationContext.xml"})
public class PayRollComponentFacadeIT {
    @Autowired
    IPayRollComponentFacade payRollComponentFacade;
    @ReplaceWithMock
    @Autowired
    IPayRollPersistenceManager payRollPersistenceManager;

我已将模拟上下文包含为 @ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {"classpath*:/MockApplicationContext.xml"})

但我还必须包含 spring 上下文 @ContextConfiguration(locations = {"classpath*:/testApplicationContext.xml"})

问候 拉吉布

【问题讨论】:

    标签: java spring mockito springmockito


    【解决方案1】:

    Springockito-annotations 可以完全避免需要额外的模拟上下文。

    只需在同一个测试用例中枚举要模拟的 DAO:

    @ReplaceWithMock
    DAO dao;
    

    此 dao 将在主应用程序上下文中自动替换。控制器会看到模拟的 bean。

    【讨论】:

    • @Autowired 必须在 @ReplaceWithMock 之前!!
    • @Autowired 仅在您需要直接在测试用例类中访问模拟实例时才需要。如果您只需要在 spring 上下文中用 mock 替换 bean,则不需要。然后所有其他 bean 将获得模拟版本。这是 Springockito 注释中最酷的功能。
    【解决方案2】:

    ContextConfiguration.locations 是一个数组,因此您可以根据需要指定任意位置。

    @ContextConfiguration(
           loader = SpringockitoContextLoader.class,
           locations = {"classpath*:/MockApplicationContext.xml",
                        "classpath*:/testApplicationContext.xml"}
    )
    

    顺便说一句:(这只是我记忆中的一个提示,我不知道问题是否仍然存在,或者我做错了什么) 很久以前,我在使用两个位置参数时注意到了一些问题,因为它接缝弹簧创建两个上下文(每个位置一个)。因此我使用一个配置文件,inculdes 两个普通配置文件。 (@见https://stackoverflow.com/a/3414669/280244

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2014-12-17
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多