使用 Visual Studio Team Services 的在线托管版本时,我的单元测试无法连接到侦听生成代理本地主机上的 TCP 端口的服务。该服务能够启动并打开 TCP 端口,但在单元测试中似乎无法访问。
错误信息:
2017-06-20T12:05:00.8231306Z ##[错误]------------
System.Net.Http.HttpRequestException:发送时发生错误
的请求。 2017-06-20T12:05:00.8231306Z ##[错误]----------------
System.Net.WebException:无法连接到远程服务器
2017-06-20T12:05:00.8231306Z ##[错误]--------------------
System.Net.Sockets.SocketException:无法建立连接
因为目标机主动拒绝127.0.0.1:41670
打开 TCP 端口的服务启动如下:
public void Start()
{
HttpPort = ObtainFreePort();
TcpPort = ObtainFreePort();
ClusterVNode node = EmbeddedVNodeBuilder.AsSingleNode()
.WithInternalTcpOn(new IPEndPoint(IPAddress.Loopback, TcpPort))
.WithExternalTcpOn(new IPEndPoint(IPAddress.Loopback, TcpPort))
.WithInternalHttpOn(new IPEndPoint(IPAddress.Loopback, HttpPort))
.WithExternalHttpOn(new IPEndPoint(IPAddress.Loopback, HttpPort))
.AddExternalHttpPrefix($"http://+:{HttpPort}/")
.RunProjections(ProjectionsMode.All)
.StartStandardProjections()
.RunInMemory()
.Build();
node.StartAndWaitUntilReady().Wait();
}
static int ObtainFreePort()
{
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.Bind(new IPEndPoint(IPAddress.Loopback, 0));
var port = ((IPEndPoint)sock.LocalEndPoint).Port;
sock.Close();
return port;
}
}
这在我的本地计算机上有效:) Visual Studio Team Services Online 不支持此功能吗?
如果您使用托管代理,则无法打开端口或更改有关计算机配置的任何内容。您需要为构建设置自己的代理。
另外,如果测试需要 TCP 通信,那么它就不再是单元测试。单元测试没有外部依赖性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)