使用Spring-boot存根的Spock无法正常工作

时间:2019-06-20 18:21:54

标签: java spring-boot testing spock

我想在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 = '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)

1 个答案:

答案 0 :(得分:1)

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