我正在为一个新应用程序构建可称为DAL的东西.不幸的是,与数据库的网络连接是一个真正的问题.
我希望能够在我的测试范围内临时阻止网络访问,以便我可以确保我的DAL在这些情况下按预期运行.
更新:有许多手动方式来禁用网络,但如果我可以在测试中启用/禁用它肯定会很好.
目前,我只是通过设置虚假静态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); } } } }
写一个包装器到你正在使用的网络类连接类(例如WebClient)和一个开关开关:)
要么是这样,要么阻止你的应用程序在防火墙中.
如果您正在为应用程序尝试完全网络中断,则可以拔下网络电缆.有时您可能拥有一个包含多个数据源的数据访问层(在不同的计算机上),在这种情况下,您可以使用像Rhino Mocks这样的模拟框架模拟测试中的异常.以下是您可能在测试中使用的一些伪代码
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"); }