0
0

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 5 years have passed since last update.

【メモ】はじめてSpringBootでSpockを書いたとき

Posted at

はじめに

現場でSpockを書く機会があったが???になった為
ざっくり流れだけ書く

テストするサンプルソース

ServiceImpl
public String send(Stiring to, String hash) {
        String url = "https://test" + "/send/" + hash;
        String strBody = createBody(url);
        return sendMail(to, strBody, hash);
    }

メールを送信するメソッド
urlを作成
メール本文を作成
宛先と本文とハッシュをがっちゃんこしてメールを送信している
returnで文字列を返す

テストするソースコードを理解する

このクラスは何をしているのか
どんなメソッドがあるのかざっくり理解しておく
後でがっつりソースコードとにらめっこすると思うのでここでウォーミングアップも兼ねて

メソッドごとにテストコード書いていく

だいたい登場するのが
setup:
when:
then:
where:
この4つ

ServiceImplTest
package demo;

import demo

@RunWith(Sputnik.class)
class ServiceImplTest extends Specification {

    def setup() {
        Service service
    }

    @Unroll
    def "正常テスト1"() {
        setup:
        service = (ServiceImpl) Spy(ServiceImpl.class, constructorArgs: [test1])
        service.createBody(_ as String) >> "dummyBody"
        service.sendMaiil(_ as String, _ as String, _ as String) >> "test"

        when:
        String testString = service.send(to, hash)

        then:
        testString == "test"

        where:
        testcase   | to          | hash
        "testCode" | "aaa@co.jp" | "testhash"

    }
}

when

まずはじめに書くのはwhen:
service.send(to, hash)を本実装と同じように実装する
ただtoとhashには事前に文字列が必要なので用意しておく※where:参照

実行後にreturnで文字列を返すためtestStringという変数に格納

where:の使い方は他にもあるためこれは一例

ここではメソッドを実行するだけ
と覚えておく

then

次にthen:に着目
testString == "test"
testStringの変数には文字列のtestが入ってるよね?の確認
実行結果を検証する

setup

最後にsetup:を実装していく
when: then: where:でテストの入口出口を作成した
あとは中身の実装を偽装実装?していくだけ
サンプルソースのsendクラスには2つのメソッドが呼び出されている
それをMock化していく※詳しくはMock・Spyで調べてください
createBody(url)
sendMail(to, strBody, hash)

そして >> "dummyBody"のように本番同様か、都合の良い結果を自分で書いてしまいましょう
_ as XXXXと記載すればやり過ごしてくれます。引数がないとエラーを起こすから
とりあえず何か入ってるてことにしといてくれる

_ as XXXXと記載しないとMock化しないので引数などは入れないでください
前まではtoをservice.createBody(to)といれてて動作しなかった
Intellijだと_ as XXXXのXXXXを勝手に保管してくれるから便利

自身のメソッドのみの試験を行いため、他のクラス、メソッドを呼び出しにいかないように偽装する
不可能な場合もたくさんあるのでその時は適宜現場の人と相談していく

おわり

だいたいの流れはこんな感じ
技術的というかどこからやればいいか
手も足もでない状態のときはこうしてコツを掴んでいった。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?