Web サービスを使用するクライアントを実装しています。依存関係を減らしたいので、Web サービスをモックすることにしました。
私は mockito を使用します。EasyMockと比べて、インターフェイスだけでなくクラスをモックできるという利点があります。しかし、それは重要ではありません。
私のテストでは、次のコードを取得しました。
// Mock the required objects
Document mDocument = mock(Document.class);
Element mRootElement = mock(Element.class);
Element mGeonameElement = mock(Element.class);
Element mLatElement = mock(Element.class);
Element mLonElement = mock(Element.class);
// record their behavior
when(mDocument.getRootElement()).thenReturn(mRootElement);
when(mRootElement.getChild("geoname")).thenReturn(mGeonameElement);
when(mGeonameElement.getChild("lat")).thenReturn(mLatElement);
when(mGeonameElement.getChild("lon")).thenReturn(mLonElement);
// A_LOCATION_BEAN is a simple pojo for lat & lon, don't care about it!
when(mLatElement.getText()).thenReturn(
Float.toString(A_LOCATION_BEAN.getLat()));
when(mLonElement.getText()).thenReturn(
Float.toString(A_LOCATION_BEAN.getLon()));
// let it work!
GeoLocationFetcher geoLocationFetcher = GeoLocationFetcher
.getInstance();
LocationBean locationBean = geoLocationFetcher
.extractGeoLocationFromXml(mDocument);
// verify their behavior
verify(mDocument).getRootElement();
verify(mRootElement).getChild("geoname");
verify(mGeonameElement).getChild("lat");
verify(mGeonameElement).getChild("lon");
verify(mLatElement).getText();
verify(mLonElement).getText();
assertEquals(A_LOCATION_BEAN, locationBean);
私のコードが示しているのは、消費するオブジェクトを「マイクロテスト」していることです。テストで生産的なコードを実装するようなものです。結果 xml の例はGeoNames の London です。私の意見では、それはあまりにも細分化されています。
しかし、すべてのステップを与えずに Web サービスをモックするにはどうすればよいでしょうか? モック オブジェクトが XML ファイルを返すようにする必要がありますか?
それはコードではなく、アプローチです。
JUnit 4.x と Mockito 1.7 を使用しています