Spock 存根没有 return 预期值

Spock stub does not return expected value

我正在尝试使用 Spock Stub 来模拟我的服务 database/repository 依赖项 class,但我遇到了一个问题,即该存根返回了一个意外的值。我不明白为什么只有当我不向模拟方法传递参数时存根才有效。

given: 'I have client data'
Client client = new Client("Foo", "bar@baz.org")

and: 'a client repository always returns the id'
clientRepository = Stub(ClientRepository)
ClientEntity ce = new ClientEntity("Foo", "bar@baz.org")
clientRepository.create(ce) >> 1

when: 'I add the client'
ClientService clientService = new ClientServiceImpl(clientRepository)
Client addedClient = clientService.addClient(client)

then: 'The client object should be populated correctly'
addedClient.getId() == 1 // This fails b/c it's returning the id as 0

但是当我使用 _ 参数时,测试通过了:

given: 'I have client data'
Client client = new Client("Foo", "bar@baz.org")

and: 'a client repository always returns the id'
clientRepository = Stub(ClientRepository)
clientRepository.create(_) >> 1

when: 'I add the client'
ClientService clientService = new ClientServiceImpl(clientRepository)
Client addedClient = clientService.addClient(client)

then: 'The client object should be populated correctly'
addedClient.getId() == 1 // This passes b/c it's returning the id as 1

这是服务class

@Service
public class ClientServiceImpl implements ClientService{

    private ClientRepository clientRepository;

    @Autowired
    ClientServiceImpl(ClientRepository clientRepository){
        this.clientRepository = clientRepository;
    }

    @Override
    public Client addClient(Client client){

        ClientEntity clientEntity = new ClientEntity(
                client.getName(),
                client.getEmailAddress()
        );

        int id = clientRepository.create(clientEntity);
        client.setId(id);

        return client;
    }
}

和 Spock 依赖项

 <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.3-groovy-2.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-spring</artifactId>
            <version>1.3-groovy-2.5</version>
            <scope>test</scope>
        </dependency>

感谢您的帮助!

如果你这样做

ClientEntity ce = new ClientEntity("Foo", "bar@baz.org")
clientRepository.create(ce) >> 1

并且存根交互没有被执行,那么因为方法参数没有按照您的期望匹配。我的猜测是 ClientEntityequals(..) 方法没有像你期望的那样工作,并且给 create(..) 的参数不完全是 ce 而是它的一个副本不满足equals(..).

解决方案:修复您的 equals(..) 方法。