2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DartでParameterized Testを実施してみる

Posted at

概要

単体テストの考え方/使い方 を読んでいたら、Parameterized Test という書き方がでてきたので、早速Dartで実践してみました。

Parameterized Test

ケースをグループ化して、一つのメソッドにまとめるもの。検証すべき事実(パターン)がたくさんある場合に、テストケースが増えすぎるのを防ぐことができる。注意事項としては、テストコードの量を減らすことと引き換えに、検証すべきことがわかりづらくなるため、正常系と異常系でケースを分けるなどの工夫が必要。

やってみよう

ShopValueの値から、SuperMarket, DrugStore, OtherStores のいずれかのインスタンスを取得するというシンプルなテストがあります。これをParameterized Testに変更してみます。

Parameterized前

SuperMarketを生成できることのテストを書きました。このまま書くとすると、ケースをコピペして、DrugStore, OtherStoresのケースも作る必要があります。

Parameterized前
void main() {
  group('Shops', () {
    test('それぞれのWhereToBuyクラスが取得できること', () {
      WhereToBuy superMarket = Shops.getWhereToBuy(ShopValue.first);
      expect(superMarket, SuperMarket());
    });
  });
}

Parameterized後

3つのケースを、1つの時とあまり変わらない量で書くことができました。特にひとつのクラスに複数のメソッドがある時に、テストケースが膨大にならずよさそうです。

Parameterizedしてみた
void main() {
  group('ShopValueからそれぞれのWhereToBuyクラスが取得できること', () {
    <ShopValue, WhereToBuy>{
      ShopValue.first: SuperMarket(),
      ShopValue.second: DrugStore(),
      ShopValue.third: OtherStores()
    }.forEach((shopValue, expected) {
      test('shopValueが $shopValue のとき、お店は $expected になる', () {
        WhereToBuy whereToBuy = Shops.getWhereToBuy(shopValue);
        expect(whereToBuy, expected);
      });
    });
  });
}

実行結果もわかりやすいです。

image.png

参考

単体テストの考え方/使い方

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?