LoginSignup
12
11

More than 5 years have passed since last update.

SpringでDIされるオブジェクトのMockテスト その2

Posted at

「SpringでDIされるオブジェクトのMockテスト」の続きです。

その後いろいろ書いていて、これが一番かなという結論に達したので紹介します。

(4) MockitoとReflectionUtilsを使う

(3)とやってることは同じです。

@ContextConfiguration(locations = "classpath:context.xml")
class ServiceASpec extends Specification {

    @Autowired
    private ServiceA serviceA

    def setup() {
        RepositoryB repositoryB = Mockito.mock(RepositoryB.class)
        ReflectionTestUtils.setField(serviceA, "repositoryB", repositoryB)
    }

    def "RepositoryBをMockにしたテスト"() {
        when:
        sut.order1("test")

        then:
        // repositoryB.save("test")が1回呼ばれた
        Mockito.verify(repositoryB).save("test")

        // 上記以外でMockが呼ばれていない
        Mockito.verifyNoMoreInteractions(repositoryB)
    }
}

Assertionの結果はこのように出力されます。わかりやすい。

Argument(s) are different! Wanted:
repositoryB.save(
    "test"
);

Actual invocation has different arguments:
repositoryB.save(
    "test1"
);
12
11
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
12
11