我是单元测试的新手,目前在寻找一种体面的方法来测试包含分支的方法时遇到了问题。
我创建了一个小演示方法,希望可以用来解释问题。
public void ExportAccounts()
{
int emptyAccounts = 0;
int nonEmptyAccounts = 0;
int errorous = 0;
string outputPath = this.GetOutputPath();
Account[] accounts = this.MyWebserviceAdapter.GetAccounts();
foreach(Account account in accounts)
{
try
{
if(account.Amount > 0)
{
this.ExportNonEmpty(outputPath, account);
nonEmptyAccounts++;
} else {
this.ExportEmptyAccount(outputPath, account);
emptyAccounts++;
}
} catch(Exception e) {
logger.error(e);
errorous++;
}
}
logger.debug(string.Format("{0} empty / {1} non empty / {2} errorous", emptyAccounts, nonEmptyAccounts, errorous));
}
我可以模拟 MyWebserviceAdapter 以返回预定义的帐户列表。我应该在同一个测试中输入一个空的和非空的帐户列表,还是应该有单独的测试?
我的 ExportNonEmpty() 和 ExportEmpty() 方法也是私有的,但确实将文件写入文件系统。我应该提供一个模拟 FileProvider 以便不触及文件系统吗?
我应该公开 ExportNonEmpty() 和 ExportEmpty() 以便能够单独测试它们吗?这些方法还包含一些 if-then-else 语句,并且可以抛出异常等等。
我发现如果我为每个代码路径创建一个测试,我将代码从一个测试复制到另一个测试 - 生成模拟等..这不是有点奇怪吗?
我应该将计数器变量公开为输出变量,以便在调用方法后能够验证它们吗?
this.GetOUTputPath() 通过静态的 ConfigurationManager 从配置文件中获取值。我应该 a) 通过为 testt 下的类创建部分模拟并覆盖 GetOutputPath 方法来模拟它,还是 b) 创建我自己的可以模拟的 ConfigurationAdapter?
我正在使用 nunit 和 Rhino Mocks。