dimanche 1 décembre 2019

Mocking in Spock framework

I tried to write test in Spock, but I have some problems. Code will tell more... My tests looks like:

class MyServiceSpec extends Specification {
    private MyService myService
    private MyDAO myDAO

    def setup() {
        myDAO = Mock(MyDAO)
        myService = new MyServiceImpl(myDAO)
    }

    def "Should get something"() {
        given:
        def user = Mock(User)
        def date = now()
        myDAO.getUsersSomethingFromDate(_ as User, _ as LocalDate) >> [ Mock(Something) ]

        when:
        myService.getUsersSomethingFromDate(user, date)

        then:
        1 * myDAO.getUsersSomethingFromDate(_ as User, _ as LocalDate)
    }
}

MyDAO is an interface.

I also tried different setup method:

    def setup() {
        myDAO = Mock(MyDAO) {
            getUsersSomethingFromDate(_ as User, _ as LocalDate) >> [ Mock(Something) ]
        }
        myService = new MyServiceImpl(myDAO)
    }

Despite I declared that method getUsersSomethingFromDate should return [ Mock(Something) ], it returns null. In the next service method run I received NullPointerException, because returned 'null' instead of list of mocked instance. The question is why mocked object with declared value to return still returns null?

Aucun commentaire:

Enregistrer un commentaire