我想在Spring Boot项目中编写Spock单元测试。当我尝试存根存储库时,它无法正常工作。

我调试它,并在测试方法中,存根看起来正确,返回预期结果。但是,当我们在服务类eventMemberService.eventMembers上调用method时,它不是从存根返回“真实”数据……这是怎么回事?

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 = '[email protected]'
    }

    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)

最佳答案

EventMemberService不是模拟对象,您期望什么?也许您忘记了将存储库存根注入该服务。如果这样做,它应该可以工作。 ;-)

07-24 20:49