如何出于测试目的模拟网络故障(在 C# 中)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/474803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to simulate network failure for test purposes (in C#)?
提问by Larsenal
I'm building what could be called the DAL for a new app. Unfortunately, network connectivity to the database is a real problem.
我正在为一个新的应用程序构建可以称为 DAL 的东西。不幸的是,与数据库的网络连接是一个真正的问题。
I'd like to be able to temporarily block network access within the scope of my test so that I can ensure my DAL behaves as expected under those circumstances.
我希望能够在我的测试范围内临时阻止网络访问,以便我可以确保我的 DAL 在这些情况下按预期运行。
UPDATE: There are many manual ways to disable the network, but it sure would be nice if I could enable/disable within the test itself.
更新:有很多手动方法可以禁用网络,但是如果我可以在测试本身中启用/禁用它肯定会很好。
采纳答案by Larsenal
For the time being, I'm just "disabling" the network by setting a bogus static IP as follows:
目前,我只是通过设置一个虚假的静态 IP 来“禁用”网络,如下所示:
using System.Management;
class NetworkController
{
public static void Disable()
{
SetIP("192.168.0.4", "255.255.255.0");
}
public static void Enable()
{
SetDHCP();
}
private static void SetIP(string ip_address, string subnet_mask)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC) {
if ((bool)objMO("IPEnabled")) {
try {
ManagementBaseObject setIP = default(ManagementBaseObject);
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
newIP("IPAddress") = new string[] { ip_address };
newIP("SubnetMask") = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
catch (Exception generatedExceptionName) {
throw;
}
}
}
}
private static void SetDHCP()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc) {
// Make sure this is a IP enabled device. Not something like memory card or VM Ware
if ((bool)mo("IPEnabled")) {
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS("DNSServerSearchOrder") = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
回答by Mostlyharmless
Try blocking the connection with a firewall midway through the session maybe?
尝试在会话中途阻止与防火墙的连接?
I like the wrapper idea as well, but thats kind of abstracting the problem and you prolly might not get exact real world behavior. Also, inserting the wrapper layer and then removing it may be more trouble than its worth.
我也喜欢包装器的想法,但那是对问题的一种抽象,你可能无法获得准确的现实世界行为。此外,插入包装层然后移除它可能比它的价值更麻烦。
Edit: Run a script that turns the Network adapter on/off randomly or at set intervals?
编辑:运行一个脚本,随机或以设定的时间间隔打开/关闭网络适配器?
回答by Andrew Rollings
Write a wrapper to the network class connectivity class you're using (e.g. WebClient) with an on-off switch :)
使用开关为您正在使用的网络类连接类(例如 WebClient)编写一个包装器 :)
Either that, or block your application in the firewall.
要么,要么在防火墙中阻止您的应用程序。
回答by Jim Blizard
Look for a WAN simulator that will allow you to restrict bandwidth (and cut it off completely) I always find it interesting to see how the user experience changes when my apps are run in a bandwidth restricted environment. Look herefor some information.
寻找一个可以让你限制带宽(并完全切断它)的 WAN 模拟器我总是觉得当我的应用程序在带宽受限的环境中运行时用户体验如何变化很有趣。看看这里的一些信息。
回答by Gulzar Nazim
There is a tool you can use for simulating High Latency and Low Bandwidth in Testing of Database Applications as explained in this blog entry.
如本博客文章所述,有一种工具可用于在数据库应用程序测试中模拟高延迟和低带宽。
回答by Rorzilla
If you are trying a complete network outage for your application unplugging the network cable will work. Sometimes you might have a data access layer with multiple data sources (on different machines) in which case you can simulate an exception in your tests with a Mock Framework like Rhino Mocks. Here is some pseudo-code that you may have in your test
如果您正在为您的应用程序尝试完全网络中断,则拔下网络电缆将起作用。有时您可能有一个包含多个数据源(在不同机器上)的数据访问层,在这种情况下,您可以使用像 Rhino Mocks 这样的 Mock 框架在测试中模拟异常。这是您可能在测试中使用的一些伪代码
void TestUserDBFailure()
{
// ***** THIS IS PSEUDO-CODE *******
//setting up the stage - retrieval of the user info create an exception
Expect.Call(_userRepository.GetUser(null))
.IgnoreArguments()
.Return(new Exception());
// Call that uses the getuser function, see how it reacts
User selectedUser = _dataLoader.GetUserData("testuser", "password");
}
回答by Rob Williams
Use mock objects to create configurable, destructible versions of the real thing--in this case, the database.
使用模拟对象来创建真实事物的可配置的、可破坏的版本——在这种情况下,是数据库。
回答by JeffK
Probably not helpful for simulating "real" network issues, but you could just point your DB connection string to a non-existent machine while within the scope of your test.
可能对模拟“真实”网络问题没有帮助,但您可以在测试范围内将数据库连接字符串指向不存在的机器。
回答by Mark Brackett
Depends on what particular network problem you wish to simulate. For most folks, it's as simple as "server unreachable", in which case you'd just try to connect to a non existent server. Be careful, though, because you want something that is routable but does not answer. Trying to connect to dkjdsjk.com will fail immediately (DNS lookup), but trying to connect to www.google.com:1433 will (probably) time out due to a firewall - which is how your app will behave when your DB server is down.
取决于您希望模拟的特定网络问题。对于大多数人来说,这就像“服务器无法访问”一样简单,在这种情况下,您只需尝试连接到不存在的服务器即可。不过要小心,因为您想要一些可路由但不响应的东西。尝试连接到 dkjdsjk.com 将立即失败(DNS 查找),但尝试连接到 www.google.com:1433 将(可能)由于防火墙而超时 - 这就是当您的数据库服务器处于运行状态时您的应用程序的行为方式下。
回答by FraDiGomma
Just found an alternative that allows to directly close TCP connections:
刚刚找到了一个允许直接关闭 TCP 连接的替代方法:
http://lamahashim.blogspot.ch/2010/03/disabling-network-using-c.html
http://lamahashim.blogspot.ch/2010/03/disabling-network-using-c.html
It is based on Windows IP Helper API (uses DllImport): http://msdn.microsoft.com/en-us/library/windows/desktop/aa366073(v=vs.85).aspx
它基于 Windows IP Helper API(使用 DllImport):http: //msdn.microsoft.com/en-us/library/windows/desktop/aa366073(v=vs.85) .aspx