2012-08-31 49 views
2

我用SpringTest和EasyMock的做我的Spring bean的單元測試。SpringTest和afterPropertiesSet方法

我的測試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(); 
    } 

} 

的方法的afterPropertiesSet初始化時的bean被自動由Spring調用。我想用EasyMock來調用doSomething方法。

我雖然這樣做在我的測試方法,但之前在我的測試方法去,因爲春天時,它初始化豆調用它的afterPropertiesSet方法被執行。

如何,我可以嘲笑我的服務存在於的afterPropertiesSet方法與SpringTest或EasyMock的?

感謝

編輯:

我指定的嘲笑服務被正確地加載在我的控制器由Spring。我的問題不是如何創建模擬(它已經可以),而是如何模擬該方法。

回答

2

你沒有提供足夠的細節,所以我給你一個的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接口。但其中一人是主要,它會被選擇用於自動裝配。而已!

想記錄或者覈實一些行爲?就在這個注入模擬您的測試:

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

    @Autowired 
    private IService iServiceMock; 
+0

更新我的問題更加全面。 – Kiva

1

不要@Autowire你的控制器,而不是編程實例就在您的測試,手動設置嘲笑服務。

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

或:

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

您的解決方案假定我有一套適用於我的控制器,情況並非如此。我想用autowired來創建一個Spring上下文。 – Kiva

+0

@Kiva爲什麼不爲你的服務創建一個包級別的setter?它只能用於同一個包中的類,比如你的測試類。 –