【问题标题】:SpringTest and afterPropertiesSetSpringTest 和 afterPropertiesSet
【发布时间】:2012-08-31 16:10:28
【问题描述】:

我使用 SpringTest 和 EasyMock 对我的 Spring bean 进行单元测试。

我的测试bean是这样的:

    @ContextConfiguration(locations = "classpath:/test/applicationContext-test.xml")
    public class ControllerTest {

        @Autowired
        private Controller controller;

        @Autowired
        private IService service;

        @Test
        public void test() {
        }
}

这是我的控制器:

@Controller
@Scope("request")
public class Controller implements InitializingBean {

    @Autowired
    private IService service;

    void afterPropertiesSet() throws Exception {
        service.doSomething();
    }

}

spring 初始化 bean 时会自动调用 afterPropertiesSet 方法。我想用 EasyMock 模拟对 doSomething 方法的调用。

我虽然在我的测试方法中执行此操作,但 afterPropertiesSet 在进入我的测试方法之前执行,因为 Spring 在初始化 bean 时会调用它。

如何使用 SpringTest 或 EasyMock 在 afterPropertiesSet 方法中模拟我的服务?

谢谢

编辑:

我指定 Spring 将模拟服务正确加载到我的 Controller 中。我的问题不是如何创建模拟(已经可以了),而是如何模拟方法。

【问题讨论】:

    标签: spring easymock spring-test


    【解决方案1】:

    你没有提供足够的细节,所以我会给你一个 Mockito 的例子。将此IService 模拟配置添加到applicationContext-test.xml 文件的开头

    <bean 
          id="iServiceMock"
          class="org.mockito.Mockito" 
          factory-method="mock"
          primary="true">
      <constructor-arg value="com.example.IService"/>
    </bean>
    

    注意到primary="true" 属性了吗? Spring 现在将找到两个实现IService 接口的类。但其中之一是primary,它将被选择用于自动装配。就是这样!

    想要记录或验证某些行为?只需将此模拟注入您的测试:

    @ContextConfiguration(locations = "classpath:/test/applicationContext-test.xml")
    public class ControllerTest {
    
      @Autowired
      private IService iServiceMock;
    

    【讨论】:

      【解决方案2】:

      不要@Autowire您的控制器,而是在您的测试中以编程方式实例化它,手动设置模拟服务。

      @Test
      public void test() {
          Controller controller = new Controller();
          controller.setMyService(mockService);
      }
      

      或:

      @Test
      public void test() {
          Controller controller = new Controller();
          controller.afterPropertiesSet();
      }
      

      【讨论】:

      • 您的解决方案假设我有一套用于我的控制器,但事实并非如此。我想使用 autowired 来获得 Spring 上下文。
      • @Kiva 为什么不为您的服务创建一个包级设置器?它仅适用于同一包中的类,例如您的测试类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2014-10-21
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多