设置 Mockito return 为除某个值以外的任何整数 [英] Set Mockito return to be any integer except a certain value

查看:68
本文介绍了设置 Mockito return 为除某个值以外的任何整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我试图返回任何不等于 1 的整数.目前我有:

Specifically, I'm trying to return any integer not equal to 1. Currently I have:

Mockito.when(dsIn.getItemNumber(1, "COLUMN")).thenReturn(0.0);

但我想要类似的东西:

Mockito.when(dsIn.getItemNumber(1, "COLUMN")).thenReturn(anyInt() != 1);

推荐答案

您实际上并不希望每次运行测试时测试用例都不同.您希望它们是可重现的,这样当您的测试失败,然后重新运行测试时,您会得到与之前相同的失败(出于相同的原因).

You don't actually want your test cases to be different every time you run your test. You want them to be reproducible, so that when your test fails, and then you re-run the test, you get the same failure (for the same reason) as before.

如果你想确保 every int 除了 1 都是有效的,你可以写一个 for循环遍历所有值,或者您可以选择一些有趣"的值,例如 02-1Integer.MAX_VALUE 等.无论哪种方式,您都应该明确说明您正在测试的值,而不是隐式(一些不是这个值的值"一个").

If you want to ensure that every int other than 1 is valid, you could write a for loop over all the values, or you could pick a few "interesting" values, like 0, 2, -1, Integer.MAX_VALUE, etc. Either way, you should be explicit about what values you're testing, rather than implicit ("some value that isn't this one").

或者,您可以随机选择一个数字并对其进行硬编码.它仍然是随机的":

Or, you can just pick a number randomly and hard-code it. It's still "random":

这篇关于设置 Mockito return 为除某个值以外的任何整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆