[英]Unit tests - What to Mock if tested method fails early?
Let's say we have the following trivial example code: 假设我们有以下简单的示例代码:
public void doXYZ(UUID uuidA, UUID uuidB, UUID uuidC){
ObjectA objectA = objectAService.read(uuidA);
ObjectB objectB = objectBService.read(uuidB);
if(!doMatch(objectA, objectB)){
throw new ObjectsDoNotMatchException(objectA);
}
ObjectC objectC = objectCService.read(uuidC);
objectC.setObjects(objectA, objectB);
objectJobService.doWork(objectC);
}
And there would be a test case which tests and expects that the exception is thrown due to some matching issues. 并且会有一个测试用例,它测试并期望由于某些匹配问题而引发异常。
Question: is it enough to Mock the first two services + the objectValidationService as all other services would not be reached anyway if the test case works? 问题:模拟前两个服务+ objectValidationService是否足够,因为如果测试用例可行,则其他所有服务都无法访问? Or should the objectCService as well as objectJobService also be mocked as they could be called and return a NullPointerException if the test does not work as expected?
还是应该模拟objectCService以及objectJobService,因为它们可能会被调用,并且如果测试无法按预期进行,则返回NullPointerException?
I often ask this kind of question if the methods are not as trivial as the shown method but instead have multiple further dependencies which should be mocked as it can be quite much work to produce a valid state for the full path (which is not being tested in this test case) for early failure cases. 我经常问这样的问题,这些方法是否不如所示的方法那么琐碎,而是具有多个其他依赖关系,应该对其进行模拟,因为为整个路径生成有效状态可能是很多工作(未经测试)在此测试用例中),用于早期失败的情况。
Edit: Let's be more concrete. 编辑:让我们更具体。 If they should be mocked: would it be enough to not specifiy the return value (eg with when()) and let them just fail or should those mocked and usually not needed services also return valid values?
如果应该对它们进行嘲笑:是否不指定返回值(例如,使用when())并让它们只是失败还是足够?应该嘲笑那些通常不需要的服务也返回有效值?
Yes: All services should be mocked. 是:应该嘲笑所有服务。
You want to be sure that there were no interactions with the objectCService
and objectJobService
when objects A and B do not match. 您要确保当对象A和B不匹配时,与
objectCService
和objectJobService
没有交互。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.