SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

DeveloperZine(デベロッパージン)- エンジニアの意思決定を支える技術情報メディア ProductZine

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

japan.internet.com翻訳記事

Javaの単体テストでランダムなデータを活用する

QaRandomizerを利用し、ランダムデータを用いた単体テストを実行

特定の型のリストからランダムな項目を取得する

 QaRandomizerには、基本的なランダムデータを抽出する機能が備わっており、さまざまな状況で使用できます。しかし場合によっては、自分で用意したデータのリストからランダムに抽出したデータを使用したいことも当然あるはずです。その場合にはQaRandomizer.getRandomItem(Set<T>)メソッドを使用します。このメソッドのパラメータは、同じ型のオブジェクトを集めたリストです。つまり、データを格納したオブジェクト(例えばBeans)のリストを渡します。するとQaRandomizer.getRandomItem(Set<T>)メソッドは、パラメータで渡されたリストの中からランダムに選択したオブジェクトを返します。

 リスト7は、リスト6およびリスト8と連携するコードで、getRandomItem()の使用例です。有限個のメールアドレスを集めたリストを作成し、そのリストからランダムな項目を取得するテストを実行するというシナリオになっています。

リスト7 モックオブジェクトと連携して型付きのリストからランダムなオブジェクトを取得する例
public void sendEmailFromFiniteListTest() throws QaRandomizerException { 
// Get a list of 6 email addresses 
Set< Email>emails = getListOfEmails(6); 
//Set up the mock for the PostalDispatcher interface PostalDispatcher
mockDispatcher = createMock(PostalDispatcher.class); 
// Set the mock Dispatcher to the Post Office object
PostOfficeImpl.getInstance().setDispatcher(mockDispatcher);
// Get an Email with data from the finite list of email addresses 
Email email = QaRandomizer.getInstance().getRandomItem(emails);
// Tell the mock framework to expect a call to the 
// dispatch()
method mockDispatcher.dispatch(email);
// Register the mock scenario 
replay(mockDispatcher); 
// Call the behavior that we're testing against
PostOfficeImpl.getInstance().send(email);
// Verify that the test passed 
verify(mockDispatcher);
}
リスト8 HashSet<Email>リストの作成
private Set< Email> getListOfEmails(int listCount) throws QaRandomizerException {
//Create the strong typed list
Set<Email> emails = new HashSet<Email>();
//Iterate through and add an email with body to the list
for (int i = 0; i < listCount; i++) {
Email email = getRandomEmailWithBody();
emails.add(email);
} 

return emails;
}

 決まった数のメールアドレスのリストを作成するという例は、やや単純すぎるかもしれません。しかし、リスト6~8の考え方を応用するのは簡単です。例えば、自動車のデータを利用するテストを作成するとします。この場合、自動車を表すAutomobileオブジェクトと、こうしたオブジェクトのデータを格納するHashSetを作成して、各Automobileオブジェクトをリストに追加していくというやり方が考えられます(リスト9を参照)。

 そして、getRandomItem()を使用して、型付きのリストからランダムなAutomobileオブジェクトを取得します(リスト10を参照)。

リスト9 QaRandomizer.getRandomItem(Set< T>)で使用されるHashSet<Automobile>の作成
/** 
* This method creates and returns a Set< Automobile>list
* 
* @return a list of type HashSet< Automobile>. HashSet< Automobile>is an * implementation of Set< T> 
*/
private Set<Automobile> getAutomobiles() {
Set< Automobile > automobiles = new HashSet< Automobile>();
automobiles.add(new Automobile("Ford", "Focus","2008"));
automobiles.add(new Automobile("Chevrolet", "Volt", "2011"));
automobiles.add(new Automobile("Volkswagen", "Beetle", "2009"));
automobiles.add(new Automobile("Chrysler", "300", "2009"));
automobiles.add(new Automobile("Nissan", "Maxima", "2008"));
return automobiles;
}

/**
* This class describes a automobile by Make, Model and Model Year 
* 
* @author Bob Reselman
*
*/
private class Automobile {
String make;
String model;
String year;
public Automobile() {super();} 
public Automobile(String make, String model, String year) {
super();
this.make = make;
this.model = model;
this.year = year;
}

@Override 
public String toString() {
return String.format("%s %s %s",this.make, this.model, this.year);
} 

/**
* @return the make 
*/ 
public String getMake() { return make; } 

/**
* @param make the make to set 
*/ 
public void setMake(String make) { this.make = make; } 
/**

* @return the model 
*/ public

String getModel() { return model; }
/** 
*
* @param model the model to set
*/
public void setModel(String model) { this.model = model; }

/**
* @return the model year
*/ 
public String getYear() { return year; } 

/** 
* @param year the model year to set
*/ 
public void setYear(String year) { this.year = year; } 
} 
リスト10 QaRandomizer.getRandomItem()によるランダムオブジェクトの取得を確認する単体テスト
/**
* This test loads a HashSet<Automobile> and runs 
* QaRandomizer.getRandomItem(Set< T>) against the list a number of times as
* defined by the variable, reps. The tests asserts that no return Automobile and 
* the previous returned Automobile match more times than the value defined in the variable,
* acceptableVariance.
* 
* @throws QaRandomizerException 
*/ 
@Test 
public void canGetRandomAutoUsingGetRandomItemTest() throws QaRandomizerException {
Set< Automobile>autos = getAutomobiles();
int matches = 0;
int reps = 30; double acceptableVariance = .2;

int i;
// Iterate against the list to make sure no two sequentially retrieved
// autos are alike. 
for (i = 0; i < reps; i++) {
Automobile auto = QaRandomizer.getInstance().getRandomItem(autos); 
Automobile otherAuto = QaRandomizer.getInstance().getRandomItem(autos);
if (auto.toString().equals(otherAuto.toString())) {
matches++;
}
}

double variance = (double) matches / (double) reps;
Assert.assertTrue(variance <= acceptableVariance,
String.format( "The test barfed on iteration %s",((Integer) i).toString())); 
} 

次のページ
制限事項と注意点

この記事は参考になりましたか?

japan.internet.com翻訳記事連載記事一覧

もっと読む

この記事の著者

japan.internet.com(ジャパンインターネットコム)

japan.internet.com は、1999年9月にオープンした、日本初のネットビジネス専門ニュースサイト。月間2億以上のページビューを誇る米国 Jupitermedia Corporation (Nasdaq: JUPM) のニュースサイト internet.comEarthWeb.com からの最新記事を日本語に翻訳して掲載するとともに、日本独自のネットビジネス関連記事やレポートを配信。

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

Bob Reselman(Bob Reselman)

Edmunds Incのシニアテクニカルライター兼テクニカルエディター。Edmunds Inc.は、多彩な情報と高い可用性を誇る、最先端のJavaベースの各種自動車情報Webサイトを運営する大手パブリッシャーである。http://www.edmunds.com/およびhttp://www.insid...

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

この記事は参考になりましたか?

この記事をシェア

CodeZine(コードジン)
https://codezine.jp/article/detail/4908 2010/03/03 14:00

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー