を定義した後@PostConstructを呼び出します。ユニットテスト:私は2つのクラス持って嘲笑行動
public MyService
{
@Autowired
private MyDao myDao;
private List<Items> list;
@PostConstruct
private void init(){
list = myDao.getItems();
}
}
を今私はユニットテストでMyService
を伴う、と私は行動MyDao
をあざけります希望しています。
XML:
<bean class = "com.package.MyService">
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.MyDao"/>
</bean>
<util:list id="responseItems" value-type="com.package.Item">
<ref bean="item1"/>
<ref bean="item2"/>
</util:list>
単体テスト:
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest{
@Autowired
MyService myService
@Autowired
MyDao myDao;
@Resource
@Qualifier("responseItems")
private List<Item> responseItems;
@Before
public void setupTests() {
reset(myDao);
when(myDao.getItems()).thenReturn(responseItems);
}
}
これで問題がMyService
Beanが作成され、嘲笑の挙動が定義される前に、その@PostConstruct Beanが呼び出されるということです。
XMLで模擬動作を定義するか、単体テストセットアップ後まで@PostConstruct
を遅延させるにはどうすればよいですか?
うん - 私は一般的に私の問題は私が解決しなければならないコードのにおいを示していることを、あなたはおそらく正しいと思います。 – dwjohnston