如何对在 try 正文中具有系统调用的异常处理程序进行单元测试
本文关键字:系统调用 异常处理程序 单元测试 try 正文 | 更新日期: 2023-09-27 18:34:20
public static string GetComputername() {
try {
return Environment.MachineName;
} catch {
return string.Empty; // make sure this never ever fails
}
}
我面临着对上述代码进行单元测试。强制系统从Environment
调用中抛出异常是否有一些魔力?我可以对方法进行更改,以便获得我想要的覆盖范围,但我也不太确定......有什么想法吗?
回答这个问题有几个方面:
- 白盒测试
真的想确保控制流按预期工作,你必须用接口将环境包装在一个单独的类中......如果你这样做,你可以模拟"MachineName"调用并模拟正常和错误的行为。这种形式的测试非常接近代码,如果实现中发生了一些小的变化,则需要花费大量精力来维护。
- 单元测试
在这里,您想从外部测试方法的行为(无需逐行测试(,如果这样做,您会发现很难测试错误情况,因为静态调用是不可模拟的......您可能想要测试正常情况,在其他情况下...那又怎样(你的决定(
- 集成测试
在这里,只有当一般内容按预期工作时,您才真的不会打扰实现细节("在使用它的函数中返回了某种名称"(
第一部分需要付出很多努力,因为您需要包装所有内容,在这种情况下,对于简单的代码来说,这似乎有点多工作......但是您需要决定要为哪个级别的粒度编写测试...
这将是包装器:
public interface ISystemWrapper
{
string MachineName();
}
public class SystemWrapper : ISystemWrapper
{
public string MachineName()
{
return Environment.MachineName;
}
}
您可以像这样修改类:
public class ToTest
{
public static ISystemWrapper SysWrapper = new SystemWrapper();
public static string GetComputername()
{
try
{
return SysWrapper.MachineName();
}
catch
{
return string.Empty; // make sure this never ever fails
}
}
}
然后在测试中模拟系统包装器
如果你可以模拟Environment
你可以制作一个没有问题的属性。
using System;
namespace TestThrowExceptionInProperty
{
class Thrower {
public int CheckMe {get{ throw new NotImplementedException (); }}
}
class MainClass
{
public static void Main (string[] args)
{
var thrower = new Thrower ();
int bye = thrower.CheckMe;
Console.WriteLine(bye);
}
}
}