grails - 如何通过模拟对象并期待一些预期结果来编写 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
}
解决方案
我不明白你的问题。测试通过。不过,您的测试语法很奇怪。这个怎么样?
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
}
推荐阅读
- python-3.x - 如何进行 72 小时倒计时
- java - 创建主题时如何从 Java Kafka AdminClient 获取详细的错误消息
- python - 使用python将逗号分隔值到Dict
- javascript - 将存储在数组中的文件附加到 HTML 文件输入 [jQuery]
- typescript - Typescript 将模板字符串编译为 es5,即使 tsconfig 目标设置为 ESNEXT
- c++ - 升级 Visual Studio 后 Bazel 不再工作
- google-apps-script - Google 脚本中的 Onchange 更改表数据
- java - 如何软删除表 A 中的记录,以及其他 3 个表中的所有引用
- r - 我试图在显示 HH:MM:SS 的值中取出秒数
- angular - 如何对 div (Cypress) 的输入进行 e2e 测试?