我如何单元测试机器具体的行为?单元测试、具体、机器、行为

2023-09-06 09:46:05 作者:月下红人已老

我测试了构建检测代理和主机名和各种事情之后,一个URL字符串的静态方法。此方法在内部依靠静态标志 System.Net.Sockets.Socket.OSSupportsIPv6 。因为它是静态的,我不能嘲笑这种依赖性。

I am testing a static method that builds a URL string after checking proxies and hostnames and all kinds of things. This method internally relies on the static flag System.Net.Sockets.Socket.OSSupportsIPv6. Because it's static, I cannot mock this dependency.

编辑:。(这是简化的倒不少......我不能修改该法的结构与标志接受真/假)

(This is simplified down a lot... I can't modify the structure of the method with the flag to accept a true/false).

在XP开发机,受到质疑该方法返回一个predictable字符串结果(在这种情况下,的http://主机名/ < /一> ....)。我们构建服务器,它支持IPv6,会返回一个完全不同的结果(这让我有点像 http://192.168.0.1:80 / ....)。请不要问为什么 - 问题是,有一些各不相同的操作系统上的依赖两个不同的输出类型

On XP development machines, the method under question returns a predictable string result (in this case, http://hostname/.... ). Our build server, which support IPv6, returns a totally different result (it gives me something like http://192.168.0.1:80/....). Please don't ask why - the point is that there are two different output types that vary on an operating system dependency.

的测试需要验证所返回的主机名或IP地址是有效的。输出为便于检查。问题是,我只能得到的可能输出之一,这取决于哪台机器上测试运行。

The test needs to validate that the returned hostname or IP address is valid. The outputs are easy to check. The problem is that I can only get one of the possible outputs, depending on which machine the test is run on.

什么是写测试在这种情况下,最好的做法是什么?难道我把一个if语句在我的测试,检查标志,然后查找两个不同的输出?这似乎粗略我,因为

What's the best practice for writing the test in this case? Do I put an if statement in my test which checks the flag and then looks for the two different outputs? This seems sketchy to me because

在测试表现不同 根据环境的不同是 运行

the test is behaving differently depending on the environment it's run in

我基本上耦合试验 该方法,因为需要 知道的方法的内部,以 建立了两种情况。

I'm basically coupling the test to the method, because you need to know the internals of the method to set up the two cases.

我是否设置了两个试验,每个环境中,简单地传递,如果他们是在错误的环境?难道我写一些复杂的正规前pression,可以分离出什么样的结果,它得到和使用更多的if / else逻辑来验证呢?

Do I set up two tests, one for each environment, that simply pass if they're in the wrong environment? Do I write some complex regular expression that can separate out what kind of result it got and use more if/else logic to verify it?

任何建议将帮助!

推荐答案

你能躲在一个抽象接口的静态方法?

Can you hide the static method behind an abstract interface?

interface ISupportIPv6
{
  bool supported { get; }
}

//class for unit testing
class TestSupportsIPv6 : ISupportIPv6
{
  public bool supported { get { return true; } }
}

//another class for more unit testing
class TestDoesNotSupportIPv6 : ISupportIPv6
{
  public bool supported { get { return false; } }
}

//class for real life (not unit testing)
class OsSupportsIPv6 : ISupportIPv6
{
  public bool supported { get {
    return System.Net.Sockets.Socket.OSSupportsIPv6; } }
}