Spock测试:调用太少

时间:2019-02-02 03:39:11

标签: spring-boot groovy spock

我正在为Service类编写Spock测试,该类的方法在Spring Boot应用程序的Dao类中调用另一个方法。但是,我得到了:

 Too few invocations for:
 1 * dao.getAddressFromSomewhere("me")   (0 invocations)
 Unmatched invocations (ordered by similarity):
 None

下面是源代码和测试代码,有人可以让我知道我做错了吗?似乎dao模拟没有被调用并完全返回“ USA”。我在网上做了一些研究,找不到我做错了。

@Service
public class ServiceClass 
{
    @Autowired
    private DaoClass dao;

    public String getAddress(String name) {         
        return dao.getAddressFromSomewhere(name);
    }
}

@Component
public class DaoClass {
     public String getAddressFromSomewhere(String name) {
     // get address from DB
     ......
     }
}

这是我的Spock测试代码:

@ContextConfiguration
@Import(ServiceClass.class)
public class Test extends Specification {

@Autowired
private DaoClass dao;
@Autowired
private ServiceClass service;

@TestConfiguration
static class MockConfig {
    def detachedMockFactory = new DetachedMockFactory()
    @Bean
    DaoClass dao() {
        return detachedMockFactory.Mock(DaoClass)
    }
}

def "Test Success Senario"() {                     
    given: "dao"
          dao.getAddressFromSomewhere("me") >> "USA";

    when: "call service "
       def actualResponse = service.getAddress("me");

    then: "dao should be invoked with given response"
       1 * dao.getAddressFromSomewhere("me")
       actualResponse == "USA"
 }
}

1 个答案:

答案 0 :(得分:3)

通过在1 * dao.getAddressFromSomewhere("me")块中编写then:,您可以覆盖dao.getAddressFromSomewhere("me") >> "USA"块中的交互given:。通过不通过>>声明返回值,您只是告诉该模拟返回null。您可以使用Spock doc检查交互顺序:

  

...在then:块中声明的交互将在进行任何其他交互之前进行匹配。这样可以覆盖在setup方法中声明的交互,然后在then:块中声明交互。

您可以通过以下几种方式重写示例:

  1. given:块中声明您的互动
def "Test Success Senario"() {
    given: "dao"
    1 * dao.getAddressFromSomewhere("me") >> "USA"

    when: "call service "
    def actualResponse = service.getAddress("me")

    then: "dao should be invoked with given response"
    actualResponse == "USA"
}
  1. when:块中声明您的互动:
def "Test Success Senario"() {
    when: "call service "
    def actualResponse = service.getAddress("me")

    then: "dao should be invoked with given response"
    1 * dao.getAddressFromSomewhere("me") >> "USA"
    actualResponse == "USA"
}