gpt4 book ai didi

java - 带有 Spring-boot stub 的 Spock 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 21:16:48 26 4
gpt4 key购买 nike

我想在 spring boot 项目中编写 spock 单元测试。当我尝试 stub 存储库时,它无法正常工作。

我调试它,在测试方法中, stub 看起来正确,返回预期结果。但是,当我们调用服务类 eventMemberService.eventMembers 上的方法时,它返回的是“真实”数据,而不是来自 stub ...它有什么问题吗?

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)

最佳答案

EventMemberService 不是 mock,你在期待什么?也许您忘记将存储库 stub 注入(inject)该服务。如果你这样做,它应该工作。 ;-)

关于java - 带有 Spring-boot stub 的 Spock 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56691847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com