单元测试调用另一个方法的方法 [英] Unit testing a method that calls another method

查看:36
本文介绍了单元测试调用另一个方法的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对调用多个方法的方法进行单元测试的最佳方法是什么,例如:

What is the best way to unit test a method that calls into multiple methods, for example:

modify(string value)
{
    if(value.Length > 5)  replaceit(value);

    else changeit(value);
}

这个伪代码有一个修改方法,它(当前)调用 replaceit()changeit().我已经为 replaceitchangeit 编写了测试,所以编写一个新的修改测试将 99% 是同一组代码.我需要测试它,因为它将来可能会改变.

This pseudo code has a modify method that (currently) calls either replaceit() or changeit(). I have already wrote tests for replaceit and changeit, so writing a new test for modify will be 99% the same set of code. I need to test it thought because it may change in the future.

那么我要复制粘贴现有的测试代码吗?将测试代码移到通用功能上?还有其他想法吗?我不确定这里的最佳做法.

So do I copy paste the existing test code? Move the test code to a common function? Any other ideas? I'm not sure of the best practice here.

推荐答案

这是一个经典的基于状态的测试与基于行为的测试场景.

This is a classic state-based test vs. behavior-based test scenario.

在这个可笑的简单示例中,测试输出很好.但在某些时候,您会遇到在执行后检查状态很复杂的测试.相反,您想检查行为(例如,验证是否使用特定值调用了 changeit).

In this ridiculously simple example testing the output is fine. At some point though, you'll run into tests where inspecting the state after execution is complicated. Instead you want to check the behavior (e.g. verify that changeit was called with a specific value).

到那时,您可能应该研究类似 Rhino.Mocks (.Net) 或 Mockito (Java) 的模拟对象框架,并开始编写更多基于界面的代码.

At that point you probably should look into a mock object framework like Rhino.Mocks (.Net) or Mockito (Java) and start writing more interface based code.

这篇关于单元测试调用另一个方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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