【发布时间】:2014-12-11 11:35:09
【问题描述】:
我在做什么
我编写了一个静态扩展方法,用于查找驻留在当前屏幕实例左侧/右侧/上方/下方的所有屏幕实例。
/// <summary>Finds all screens in the specified directions.</summary>
/// <param name="source">The screen to search around.</param>
/// <param name="directions">The directions to search in.</param>
/// <param name="excludeScreens">Any number of screens to exclude. The source screen is always excluded.</param>
/// <returns>A <see cref="T:Collection{T}"/> of <see cref="Screen"/> containing the found screens.</returns>
public static Collection<Screen> FindAll(this Screen source, ScreenSearchDirections directions, params Screen[] excludeScreens) {
if (source == null)
throw new ArgumentNullException("source");
// Always exclude the source screen.
if (excludeScreens == null)
excludeScreens = new[] { source };
else if (!excludeScreens.Contains(source))
excludeScreens = new List<Screen>(excludeScreens) { source }.ToArray();
// No direction is any direction.
if (directions == ScreenSearchDirections.None)
directions = ScreenSearchDirections.Any;
var result = new Collection<Screen>();
foreach (var screen in Screen.AllScreens.Where(screen => !excludeScreens.Contains(screen))) {
// These are "else if" because otherwise we might find the same screen twice if our directions search for example left and above and the screen
// satisfies both those conditions.
if (directions.HasFlag(ScreenSearchDirections.Left) && screen.Bounds.Right <= source.Bounds.Left)
result.Add(screen);
else if (directions.HasFlag(ScreenSearchDirections.Right) && screen.Bounds.Left >= source.Bounds.Right)
result.Add(screen);
else if (directions.HasFlag(ScreenSearchDirections.Above) && screen.Bounds.Bottom <= source.Bounds.Top)
result.Add(screen);
else if (directions.HasFlag(ScreenSearchDirections.Below) && screen.Bounds.Top >= source.Bounds.Bottom)
result.Add(screen);
}
return result;
}
当然欢迎对代码提出建设性建议。
我需要什么
我当然是对我所有的代码进行单元测试,在这种情况下,我无法进行 TDD(测试驱动开发),因为我根本无法理解应该如何测试这个操作。所以我写了实现,希望在写完之后弄清楚。
我仍然无法理解这个。
由于 Screen 的 .Net 实现没有任何构造函数可以采用IScreen 接口,也没有 IScreen 接口开始,我将如何为我的测试进行设置,我可以欺骗我有...说超过 10 个屏幕/监视器以任何首选布局连接到我的系统以进行测试?
我查看了Microsoft Fakes shim 示例,但仍然没有深入了解。
问题是,我怎样才能通过覆盖Screen constructor来伪造10多个屏幕?
根据我的实现,我只需要屏幕边界,所以我认为我不需要担心 .Net 中 Screen 类的其他实现。只要我可以替换(填充)屏幕类的构造函数以将边界字段设置为我将在我的设置中提供的字段,我将是金色的,对吗?
除非在这里有人会发现我的推理有缺陷!
注意,虽然我很欣赏这里的一些人有不同的意见和观点,但我会谦虚地要求您保持谦虚并以建设性的方式提出您的论点。如果我做错了什么,请告诉我如何解决这个错误。
我一次又一次地在 SE 网络上提问时,有人说我错了,但没有建议我如何才能变得正确。感谢您的考虑。
【问题讨论】:
-
您只需要测试这一种方法吗?在这种情况下,您应该为每个测试用例制作模拟对象并将其传递给您的方法。您需要模拟 Bounds 和 AllScreens 属性。
-
@gabba 你能给我举个例子来说明我如何模拟 AllScreens 属性,我还需要实例化
Screen对象吗?
标签: c# .net unit-testing microsoft-fakes