Spring Boot 斯波克试验:调用过少

4ktjp1zp  于 2023-01-02  发布在  Spring
关注(0)|答案(1)|浏览(128)

我正在为一个Service类编写Spock测试,这个Service类的方法调用了一个Sping Boot 应用程序中Dao类的另一个方法。

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

下面是源代码和测试代码,有人能告诉我哪里做错了吗?看起来dao mock根本没有被调用并返回“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"
 }
}
wgx48brx

wgx48brx1#

通过在then:块中写入1 * dao.getAddressFromSomewhere("me"),您只需覆盖given:块中的交互dao.getAddressFromSomewhere("me") >> "USA"。通过不通过>>声明返回值,您只需告诉模拟返回null。您可以使用以下命令检查交互顺序:
...在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.在then:块中声明您的交互:

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

相关问题