【问题标题】:Mocking services with spring boot and Spock使用 spring boot 和 Spock 模拟服务
【发布时间】:2016-12-21 04:45:43
【问题描述】:

我有一个使用另一个服务的服务,我想模拟出来。

@Service
public class CustomerService {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private MyHelper myHelper;

    public Office createOfficeAccount(Office commonOffice) throws Exception {

      // this line calls another service via http, I want to mock it:
      Account newAccount = myHelper.createAccount(officeAccount);
      return customerRepository.save(customer);
}

这是我的测试课:

class KillBillCustomerServiceTest extends BaseSpecification {

    @Autowired
    private CustomerService customerService = Mock(CustomerService)

    @Autowired
    private PatientRepository patientRepository = Mock(PatientRepository)

    @Autowired
    private MyHelper kbHelper = Mock(MyHelper)

    def setup() {
        customerService.setPatientRepository(patientRepository)
        customerService.setMyHelper(kbHelper)
    }

    def "create new Account from Common Office"() {

        def commonOffice = createOfficeForTests()
        CustomerService customerService = new CustomerService (myHelper: kbHelper)

        when:
        kbHelper.createAccount(commonOffice) >> new Account() // want to mock it, but it is still calling the actual class to try and make the network call 
}

我的问题是如何模拟我的 MyHelper 类,以便它实际上不会尝试进行真正的调用,而只是返回一个存根对象?

【问题讨论】:

  • 那是给 Mockito 的,我认为它与我上面所做的没有什么不同。

标签: spring-boot spock


【解决方案1】:

我认为您不能在 when 块中指定期望,这是这里的根本原因。

检查Spock interaction testing tutorial。它有一个名为“在哪里声明交互”的部分,它指出您只能在“设置”(给定)或“然后”块中声明期望。

这是在我的机器上运行的这种交互的简化示例:

interface Account {}

class SampleAccount implements Account {}


interface DependentService {
   Account createAccount(int someParam)
}

class DependentServiceImpl implements DependentService {

    Account createAccount(int someParam) {
       new SampleAccount()
    }
}


class MyService {

    private DependentService service

    public MyService(DependentService dependentService) {
        this.service = dependentService
}

public Account testMe(int someParam) {
    service.createAccount(someParam)
}

}

在这里您可以看到一些要测试的服务(MyService),它依赖于 DependantService 接口(我使用接口是因为我的示例项目的类路径中没有 CGLIB,这并不重要你的问题)。

这里是 spock 中的一个测试:

class SampleSpec extends Specification {

 def "check"() {
    setup:
    def mockDependentService = Mock(DependentService)
    def mockAccount          = Mock(Account)
    1 * mockDependentService.createAccount(5) >> mockAccount
    MyService testedObject  = new MyService(mockDependentService)
    when:
    def expectedAccount = testedObject.testMe(5)
    then:
    expectedAccount == mockAccount
  }
}

如您所见,我在此处的给定块中设定了我的期望。

【讨论】:

  • 完美的答案,这让我克服了困难,所以我现在可以模拟其中一个 @Autowired 类以返回一个存根的对象进行测试。感谢您的大力帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2016-11-27
相关资源
最近更新 更多