Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@nyasba

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

「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"
);
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
10
Help us understand the problem. What are the problem?