使用spring boot和Spock进行模拟服务

时间:2016-12-21 04:45:43

标签: spring-boot spock

我有一项使用其他服务的服务,我想嘲笑它。

@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类,以便它实际上不会尝试进行真正的调用,而只是返回一个存根对象?

1 个答案:

答案 0 :(得分:2)

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

检查Spock interaction testing tutorial。它有一个名为“Where to Declare Interactions”的部分,它声明您可以在“setup”(给定)或“then”块中声明期望。

以下是在我的机器上运行的此类交互的简化示例:

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

如你所见,我已经在给定的块中设定了我的期望。