jeudi 20 juin 2019

Spock with Spring-boot stubbing doesn't work correctly

I would like to write spock unit test in spring boot project. When I'm trying to stub repository it doesn/t work correctly.

I debug it and in the test method the stub looks correct, return expected result. But when we call method on the service class eventMemberService.eventMembers it's return "real" data not from the stub... What is wrong with it ?

import com.ostrouchprzemyslaw.willyoube.repositories.EventMemberRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Shared
import spock.lang.Specification

@SpringBootTest
class EventMemberServiceImplTest extends Specification {

    @Shared
    EventMember eventMember

    @Autowired
    EventMemberService eventMemberService

    EventMemberRepository eventMemberRepository = Stub(EventMemberRepository.class)

    def setupSpec(){
        eventMember = new EventMember()
        eventMember.firstName = 'Przemek'
        eventMember.lastName = 'Ostrouch'
        eventMember.email = 'przemek@gmail.com'
    }

    def "When call getEventMembers it list all members"() {

        given:
        def mockListOfMembers = new ArrayList<EventMember>()
        mockListOfMembers.add(eventMember)

        when:
        eventMemberRepository.findAll() >> mockListOfMembers
        def result = eventMemberService.eventMembers

        then:
        result == mockListOfMembers
    }

public class EventMemberServiceImpl implements EventMemberService {

    private EventMemberRepository eventMemberRepository;

    public EventMemberServiceImpl(EventMemberRepository eventMemberRepository) {
        this.eventMemberRepository = eventMemberRepository;
    }

    @Override
    public List<EventMember> getEventMembers() {
        List<EventMember> returnList = new ArrayList<>();
        eventMemberRepository.findAll().forEach(returnList::add);
        return returnList;
    }

Expected result: eventMemberService.eventMembers will return list with one eventMember, but actual result is empty list (there are no any data in DB)

Aucun commentaire:

Enregistrer un commentaire