【发布时间】:2012-08-03 08:50:13
【问题描述】:
我有一个关于测试的问题。
我有一个返回异常的类。在这个类中,我有两种不同的方法,它们只返回两种不同类型的异常,一种返回所有异常(两种类型)
这是示例代码:
public interface IAnomalyService
{
IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2);
IList<Anomaly> GetAnomalies_OfTypeA(object parameter1);
IList<Anomaly> GetAnomalies_OfTypeB(object parameter2);
}
public class AnomalyService : IAnomalyService
{
public IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2)
{
var lstAll = new List<Anomaly>();
lstAll.AddRange(GetAnomalies_OfTypeA(parameter1));
lstAll.AddRange(GetAnomalies_OfTypeB(parameter2));
return lstAll;
}
public IList<Anomaly> GetAnomalies_OfTypeA(object parameter1)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 1 } };
}
public IList<Anomaly> GetAnomalies_OfTypeB(object parameter2)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 2 } };
}
}
class Anomaly
{
public int Id { get; set; }
}
我为检索 A 型和 B 型异常的两种方法(GetAnomalies_OfTypeA 和 GetAnomalies_OfTypeB)创建了测试。 现在我想测试函数 GetAllAnomalies 但我不确定我必须做什么。
我认为我必须对其进行测试: 1) 将 AnomalyService 类中的 GetAnomalies_OfTypeA 和 GetAnomalies_OfTypeB 声明为虚拟,模拟 AnomalyService 类,使用 Moq 可以将 CallBase 设置为 true 并模拟 GetAnomalies_OfTypeA 和 GetAnomalies_OfTypeB 这两个方法。
2) 将 GetAllAnomalies 方法移到另一个名为 AllAnomalyService 的类(带有接口 IAllAnomalyService)中,并在其构造函数中传递一个 IAnomalyService 接口,然后我可以测试 GetAllAnomalies 模拟 IAnomalyService 接口。
我是单元测试的新手,所以我不知道哪种解决方案更好,是其中一种还是另一种。 你能帮帮我吗?
谢谢你 卢卡
【问题讨论】:
标签: unit-testing testing mocking