【问题标题】:Spock stub does not return expected valueSpock 存根未返回预期值
【发布时间】:2020-03-29 17:42:50
【问题描述】:

我正在尝试使用 Spock Stub 在我的服务类中模拟数据库/存储库依赖项,但我遇到了存根返回意外值的问题。我不明白为什么存根仅在我不将参数传递给模拟方法时才有效。

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

这里是服务类

@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>

感谢您的帮助!

【问题讨论】:

    标签: unit-testing groovy spock


    【解决方案1】:

    如果你这样做

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

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

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

    【讨论】:

    • 我覆盖了 ClientEntity 中的 equals 方法,但没有解决问题
    • 改变了 equals() 的实现并且它起作用了。
    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2013-09-04
    • 2016-02-13
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多