首页 > 解决方案 > 如何通过模拟对象并期待一些预期结果来编写 Spock 单元测试

问题描述

我正在尝试为添加 2 个数字编写单元测试,它正在调用 Service 类 add method() 并且还有一个类 HelperAdd 是从 add() 方法调用的

在单元测试用例中,我的预期结果与单元测试类中硬编码的结果不同,如何解决这个问题。我在代码中做错了什么吗?

单元测试类——

class ControllerTest extends Specification {

Service src
HelperAdd hd

def setup() {
    hd = Mock()

    src = new Service(
            hd: hd
    )
}

    def "Add 2 numbers"() {
        AddModel request = new AddModel()

    given: "input"
    request.setA(2)
    request.setB(3)
    when:
    src.add(request)
    then:
    1 * hd.add(_) >> 2
    expect:"4"
    }
}


Service class --

class Service {

    @Autowired
    HelperAdd hd

    @PostMapping(value="/getdocuments")
    def add(@RequestBody AddModel request) {
        int a = request.a
        int b = request.b
        int d = hd.add(a)
        int c = a+d
        return c
    }
}


HelperAdd class--

class HelperAdd {

    def add(int a)
    {
        int k = a+4
        return k
    }

}

Model class --

@Canonical
class AddModel {

    int a
    int b

}

标签: grailsgroovyjunitspock

解决方案


我不明白你的问题。测试通过。不过,您的测试语法很奇怪。这个怎么样?

def "Add 2 numbers"() {
  given: "input"
  def request = new AddModel(a: 2, b: 3)
  when:
  def result = src.add(request)
  then:
  1 * hd.add(_) >> 2
  result == 4
}

推荐阅读