Spring boot 使用spring boot和Spock模拟服务

Spring boot 使用spring boot和Spock模拟服务,spring-boot,spock,Spring Boot,Spock,我有一个使用另一个服务的服务,我想模拟它 @Service public class CustomerService { @Autowired private CustomerRepository customerRepository; @Autowired private PatientRepository patientRepository; @Autowired private MyHelper myHelper; publi

我有一个使用另一个服务的服务,我想模拟它

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

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

检查一下。它有一个名为“在何处声明交互”的部分,它声明您只能在“设置”(给定)或“然后”块中声明期望

下面是在我的机器上工作的这种交互的简化示例:

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),它取决于服务接口(我使用接口,因为我的示例项目的类路径中没有CGLIB,就您的问题而言,这并不重要)

这是斯波克的一个测试:

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

正如您所看到的,我已经在这里的给定块中设置了我的期望值。

请查看这是针对Mockito的,我不认为这与我在上面所做的有什么不同。完美的答案,这让我克服了困难,因此我现在可以模拟@Autowired类之一,返回一个存根对象进行测试。谢谢你的帮助!