2014/09/23

[spring] 用 Mockito 對 @Autowired 物件作單元測試

在 spring 大量改用 @Autowired 注入後,程式碼中的 getter & setter 逐步移除,讓單元測試變成卡卡的,之前作法是將物件 mock 後再由 setter 設定到 bean 中,但沒有 setter 後該怎麼處理呢? 
搜尋後發現大致有兩種作法,一為用 utility class 來設定或是用 SpringJUnit4ClassRunner
1. ReflectionTestUtils 來設定,需要於 pom.xml 新增 spring-test framework。
http://stackoverflow.com/questions/3660933/spring-3-autowiring-and-junit-testing
public class A {
    B b;
}
@Test
public void init() {
    A a = new A();
    B b = Mockito.mock(B.class);
    ReflectionTestUtils.setField(a, "b", b);
}
2. 使用 spring-test framework 提供的 SpringJUnit4ClassRunner
http://stackoverflow.com/questions/19299513/spring-junit-how-to-mock-autowired-component-in-autowired-component

沒有留言:

張貼留言