Spring 弹簧试验和后性能试验

Spring 弹簧试验和后性能试验,spring,easymock,spring-test,Spring,Easymock,Spring Test,我使用SpringTest和EasyMock对我的SpringBean进行单元测试 我的测试bean如下所示: @ContextConfiguration(locations = "classpath:/test/applicationContext-test.xml") public class ControllerTest { @Autowired private Controller controller; @Autowi

我使用SpringTest和EasyMock对我的SpringBean进行单元测试

我的测试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时,会自动调用AfterPropertieSet方法。我想用EasyMock模拟对doSomething方法的调用

我想在我的测试方法中这样做,但是afterPropertieSet在我的测试方法中执行之前,因为Spring在初始化bean时调用它

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

谢谢

编辑:


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

您没有提供足够的详细信息,因此我将给您一个Mockito示例。将此
IService
mock配置添加到
applicationContext test.xml
文件的开头:

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

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

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


您的解决方案假设我有一套控制器,但事实并非如此。我想使用autowired创建Spring上下文。@Kiva为什么不为您的服务创建包级别设置器?它只对同一包中的类可用,例如测试类。
@Test
public void test() {
    Controller controller = new Controller();
    controller.setMyService(mockService);
}
@Test
public void test() {
    Controller controller = new Controller();
    controller.afterPropertiesSet();
}