public void Setup() { // MockLmsService.Setup(l => l.GetIDataContext()).Returns(MockDataContext.Object); MockStorage.Protected().Setup <IDataContext>("GetDbContext").Returns(MockDataContext.Object); // MockStorage.Setup(s => s.SendEmail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true); MockStorage.Setup(s => s.GetUserRoles(It.IsAny <string>())).Returns((string username) => GetUserRoles(username)); }
public async Task FlushHistoryTest() { StorageServiceExtend sse = (StorageServiceExtend)ServiceManager.StorageService; MockStorage mockStorage = new MockStorage(); sse.SetStorage(mockStorage); mockStorage.UndeliveredActions = new List <HistoryAction> { new HistoryAction() }; mockStorage.UndeliveredEvents = new List <HistoryEvent> { new HistoryEvent() }; MockApiConnection connection = (MockApiConnection)ServiceManager.ApiConnction; IStorageService service = ServiceManager.StorageService; connection.FailNetwork = true; Assert.IsFalse(await service.FlushHistory(), "Flushing History not failed"); connection.FailNetwork = false; Assert.IsTrue(mockStorage.UndeliveredEvents.Count != 0, "Event were resetet"); Assert.IsTrue(mockStorage.UndeliveredActions.Count != 0, "Actions were resetet"); Assert.IsTrue(await service.FlushHistory(), "Flushing History not succeed"); Assert.IsTrue(mockStorage.UndeliveredEvents.Count == 0, "Event were not marked as send"); Assert.IsTrue(mockStorage.UndeliveredActions.Count == 0, "Actions were not marked as send"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin(); builder.AllowAnyMethod(); builder.AllowAnyHeader(); }) ); var mockStorage = new MockStorage(); var mockGameSessionStorage = new MockGameSessionStorage(); services.AddSingleton <IErrandStorage>((s) => mockStorage); services.AddSingleton <IGameStorage>((s) => mockStorage); services.AddSingleton <IGameErrandStorage>((s) => mockStorage); services.AddSingleton <IGameSessionStorage>((s) => mockGameSessionStorage); services.AddSingleton <IGameSessionEventStorage>((s) => mockGameSessionStorage); services.AddSingleton <IGameSessionErrandStorage>((s) => mockGameSessionStorage); services.AddSingleton <IGameSessionService, GameSessionService>(); services.AddMvc(); services.AddSignalR(options => { options.EnableDetailedErrors = true; }); }
public void FactorsTableIsWritten() { // When report gets an oncommencing it should write a _Factors table to storage. var sim = new Simulation(); sim.Descriptors = new List <SimulationDescription.Descriptor>(); sim.Descriptors.Add(new SimulationDescription.Descriptor("Experiment", "exp1")); sim.Descriptors.Add(new SimulationDescription.Descriptor("SimulationName", "sim1")); sim.Descriptors.Add(new SimulationDescription.Descriptor("FolderName", "F")); sim.Descriptors.Add(new SimulationDescription.Descriptor("Zone", "z")); sim.Descriptors.Add(new SimulationDescription.Descriptor("Cultivar", "cult1")); sim.Descriptors.Add(new SimulationDescription.Descriptor("N", "0")); var report = new Report() { VariableNames = new string[0], EventNames = new string[0] }; var storage = new MockStorage(); Utilities.InjectLink(report, "simulation", sim); Utilities.InjectLink(report, "locator", new MockLocator()); Utilities.InjectLink(report, "storage", storage); Utilities.InjectLink(report, "clock", new MockClock()); var events = new Events(report); events.Publish("FinalInitialise", new object[] { report, new EventArgs() }); Assert.AreEqual(storage.tables[0].TableName, "_Factors"); Assert.AreEqual(Utilities.TableToString(storage.tables[0]), $"ExperimentName,SimulationName,FolderName,FactorName,FactorValue{Environment.NewLine}" + $" exp1, sim1, F, Cultivar, cult1{Environment.NewLine}" + $" exp1, sim1, F, N, 0{Environment.NewLine}"); }
public async Task DisableChannelDuringSendingLogs(int countLogs) { try { // Prepare data. MockStorage storage = new MockStorage(); var appSecret = Guid.NewGuid().ToString(); Channel channel = new Channel(ChannelName, MaxLogsPerBatch, new TimeSpan(), MaxParallelBatches, appSecret, _mockIngestion.Object, storage); SetupEventCallbacks(); // Run methods in parallel for (int i = 0; i < countLogs; i++) { channel.EnqueueAsync(new TestLog()).RunNotAsync(); } channel.SetEnabled(false); // Wait when tasks will be finalized. await Task.Delay(1000); } catch (StatefulMutexException) { // Crash test if was generated StatefulMutexException error. Assert.Fail(); } }
public void CallWebService_should_return_false_if_HttpStatusCode_is_Forbidden() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); var requestProxy = new PProxyHttpWebRequest(); requestProxy.ExcludeGeneric().DefaultBehavior = IndirectionBehaviors.DefaultValue; var responseProxy = new PProxyHttpWebResponse(); responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.Forbidden; requestProxy.GetResponse().Body = @this => responseProxy; // To improve robustness against unintended modification, you should verify inputs to side-effects by Moq. // For example, the original test will pass even if you unintendedly changed the original production code as follows: // var request = CreateWebRequest(url); // -> var request = CreateWebRequest("Foo"); var url = "testService"; PWebRequest.CreateString().BodyBy(ms).Expect(_ => _(url)).Returns(requestProxy); // Act var actual = new WebServiceClient().CallWebService(url); // Assert Assert.IsFalse(actual); ms.Verify(); } }
public void Setup() { simulations = new Simulations() { Children = new List <IModel>() { new Simulation() { Children = new List <IModel>() { new MockStorage(), new MockSummary(), new Clock() { StartDate = new DateTime(2017, 1, 1), EndDate = new DateTime(2017, 1, 10) }, new Report() { VariableNames = new string[] { }, EventNames = new string[] { "[Clock].EndOfDay" }, } } } } }; Utilities.InitialiseModel(simulations); simulation = simulations.Children[0] as Simulation; runner = new Runner(simulation); storage = simulation.Children[0] as MockStorage; clock = simulation.Children[2] as Clock; report = simulation.Children[3] as Report; }
public void CallWebService_should_return_false_if_HttpStatusCode_is_Forbidden() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); var requestProxy = new PProxyHttpWebRequest(); requestProxy.ExcludeGeneric().DefaultBehavior = IndirectionBehaviors.DefaultValue; var responseProxy = new PProxyHttpWebResponse(); responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.Forbidden; requestProxy.GetResponse().Body = @this => responseProxy; // To improve robustness against unintended modification, you should verify inputs to side-effects by Moq. // For example, the original test will pass even if you unintendedly changed the original production code as follows: // var request = CreateWebRequest(url); // -> var request = CreateWebRequest("Foo"); var url = "testService"; PWebRequest.CreateString().BodyBy(ms).Expect(_ => _(url)).Returns(requestProxy); // Act var actual = new WebServiceClient().CallWebService(url); // Assert Assert.IsFalse(actual); ms.Verify(); } }
public void CallWebService_should_set_HttpWebRequest_to_request_textxml_content() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); // And also, you can verify whether HttpWebRequest is set intendedly if you use Moq. var requestProxy = new PProxyHttpWebRequest(); requestProxy.ContentTypeSetString().BodyBy(ms).Expect(_ => _(requestProxy, "text/xml;charset=\"utf-8\"")); requestProxy.MethodSetString().BodyBy(ms).Expect(_ => _(requestProxy, "GET")); requestProxy.TimeoutSetInt32().BodyBy(ms).Expect(_ => _(requestProxy, 1000)); requestProxy.CredentialsSetICredentials().BodyBy(ms).Expect(_ => _(requestProxy, CredentialCache.DefaultNetworkCredentials)); var responseProxy = new PProxyHttpWebResponse(); responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.OK; requestProxy.GetResponse().Body = @this => responseProxy; var url = "testService"; PWebRequest.CreateString().Body = @this => requestProxy; // Act var actual = new WebServiceClient().CallWebService(url); // Assert Assert.IsTrue(actual); ms.Verify(); } }
public static MockStorage AutoBodyBy(this PProxyProcess proc, MockStorage ms) { { var m = proc.StartInfoGet().BodyBy(ms); m.Setup(_ => _(It.IsAny <Process>())).Returns(new ProcessStartInfo()); ms.Set(proc.StartInfoGet, m); } { var m = proc.MainModuleGet().BodyBy(ms); m.Setup(_ => _(It.IsAny <Process>())).Returns(new PProxyProcessModule()); ms.Set(proc.MainModuleGet, m); } { var m = proc.CloseMainWindow().BodyBy(ms); m.Setup(_ => _(It.IsAny <Process>())).Returns(true); ms.Set(proc.CloseMainWindow, m); } return(ms); }
public void RestartCurrentProcess_should_organize_command_line_arguments_if_they_contain_double_quote() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms). Customize(m => m. Do(PEnvironment.GetCommandLineArgs).Setup(_ => _()).Returns(new[] { Guid.NewGuid().ToString(), "a a", "\"b\"bb", "c" }) ); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.Is<ProcessStartInfo>(x => x.Arguments == "\"a a\" \"\\\"b\\\"bb\" \"c\"" ))).Returns(new PProxyProcess()) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act var result = ULProcessMixin.RestartCurrentProcess(); // Assert Assert.IsTrue(result); } }
public void RestartCurrentProcess_should_return_false_if_user_cancelled_starting_process() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.IsAny<ProcessStartInfo>())).Throws(new Win32Exception(1223)) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act var result = ULProcessMixin.RestartCurrentProcess(); // Assert Assert.IsFalse(result); } }
public void testFlushStopsAfterFirstFailure() { var storage = new MockStorage(); var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString()); var mockEndpoint = new MockEndpoint() { Response = false }; AsyncEmitter e = new AsyncEmitter(mockEndpoint, queue, sendLimit: 1); for (int i = 0; i < 100; i++) { var p = new Payload(); p.AddDict(new Dictionary <string, string>() { { "foo", "bar" } }); e.Input(p); } Assert.AreEqual(100, storage.TotalItems); Assert.IsFalse(e.Running); e.Flush(true); Assert.IsFalse(e.Running); Assert.AreEqual(1, mockEndpoint.CallCount); Assert.AreEqual(0, mockEndpoint.Result.SuccessIds.Count); Assert.AreEqual(1, mockEndpoint.Result.FailureIds.Count); Assert.AreEqual(100, storage.TotalItems); }
public void RestartCurrentProcess_should_throw_exception_as_it_is_except_for_Win32Exception() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.IsAny<ProcessStartInfo>())).Throws(new FileNotFoundException()) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act, Assert ExceptionAssert.Throws<FileNotFoundException>(() => ULProcessMixin.RestartCurrentProcess()); } }
public void OneOfOfT_should_throw_NotSupportedException_because_we_cannot_extract_mock_from_IQueryable() { // Arrange var ms = new MockStorage(MockBehavior.Default); // Act, Assert Assert.Throws <NotSupportedException>(() => ms.OneOf <ICloneable>()); }
public void OneOfOfTExpressionOfFuncOfTOfBoolean_should_throw_NotSupportedException_because_we_cannot_extract_mock_from_IQueryable() { // Arrange var ms = new MockStorage(MockBehavior.Default); // Act, Assert Assert.Throws <NotSupportedException>(() => ms.OneOf <ICloneable>(_ => _ is IComparable)); }
public void Setup() { storage = new MockStorage(); markets = Enumerable.Range(1, 2).ToList(); historyLength = 100; analyticsManager = new AnalyticsManager(storage, new List <double> { 1 }, markets, new List <OrderInfo>(), historyLength); }
public static void AutoBodyBy(MockStorage ms) { var proc = new PProxyProcess(); proc.AutoBodyBy(ms); ms.Customize(c => c.Do(PProcess.GetCurrentProcess).Setup(_ => _()).Returns(proc)). Customize(c => c.Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.IsAny <ProcessStartInfo>())).Returns(proc)); }
public void CreateOfTMockBehavior_can_create_specified_behavior_mock() { // Arrange var ms = new MockStorage(MockBehavior.Default); var m = ms.Create <ICloneable>(MockBehavior.Strict); // Act, Assert Assert.Throws <MockException>(() => m.Object.Clone()); }
public static void AutoBodyBy(this PProxyProcess proc, MockStorage ms) { var procMod = new PProxyProcessModule(); procMod.AutoBodyBy(ms); ms.Customize(c => c.Do(proc.StartInfoGet).Setup(_ => _(It.IsAny <Process>())).Returns(new ProcessStartInfo())). Customize(c => c.Do(proc.MainModuleGet).Setup(_ => _(It.IsAny <Process>())).Returns(procMod)). Customize(c => c.Do(proc.CloseMainWindow).Setup(_ => _(It.IsAny <Process>())).Returns(true)); }
public void Setup() { // MockLmsService.Setup(l => l.GetIDataContext()).Returns(MockDataContext.Object); MockStorage.Protected().Setup <IDataContext>("GetDbContext").Returns(MockDataContext.Object); MockStorage.Protected().Setup <string>("GetPath").Returns(Path.Combine(ConfigurationManager.AppSettings["PathToIUDICO.UnitTests"], "IUDICO.LMS")); // MockStorage.Setup(s => s.SendEmail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true); MockStorage.Setup(s => s.GetUserRoles(It.IsAny <string>())).Returns( (string username) => GetUserRoles(username)); MockStorage.Setup(s => s.GetGroupsByUser(It.IsAny <User>())).Returns((User user) => GetGroupsByUser(user)); }
public void CreateOfTObjectArray_can_create_specified_behavior_mock_of_the_type_that_has_constructor_with_parameters() { // Arrange var ms = new MockStorage(MockBehavior.Default); var m = ms.Create <ConstructorWithParameters>(MockBehavior.Strict, 42); m.Setup(_ => _.Parse("cba")).Returns(23); // Act, Assert Assert.Throws <MockException>(() => m.Object.Parse("abc")); }
/// <summary> /// Returns value for the given key. /// If the key does not exists, returns the value indicated by defaultValue parameter /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public override string GetValue(string key, string defaultValue = null) { base.GetValue(key, defaultValue); if (MockStorage.ContainsKey(key)) { return(MockStorage[key]); } return(defaultValue); }
public IActionResult Redirect(int id) { Url url = MockStorage.GetById(id); if (url == null) { return(BadRequest("No record found with the specified key")); } return(Redirect(url.OriginalUrl)); }
public void CanIAddtoStorage() { var url = new Url(); url.OriginalUrl = "http://cool.xyz"; url.Active = true; var inserted = MockStorage.Add(url); Assert.NotNull(inserted); Assert.Equal(url.OriginalUrl, inserted.OriginalUrl); }
/// <summary> /// Deletes key from the collection, if it exists /// Returns true, if the key exists. False, if it does not exist /// </summary> /// <param name="key"></param> /// <returns></returns> public override bool DeleteKey(string key) { base.DeleteKey(key); if (MockStorage.ContainsKey(key)) { MockStorage.Remove(key); return(true); } return(false); }
public void ExcelWeatherFileTest() { Simulation baseSim = new Simulation(); baseSim.Name = "Base"; string weatherFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".xlsx"); using (FileStream file = new FileStream(weatherFilePath, FileMode.Create, FileAccess.Write)) { Assembly.GetExecutingAssembly().GetManifestResourceStream("UnitTests.Weather.WeatherTestsExcelFile.xlsx").CopyTo(file); } var excelWeather = new Models.Weather() { Name = "Weather", Parent = baseSim, FullFileName = weatherFilePath, ExcelWorkSheetName = "Sheet1" }; Clock clock = new Clock() { Name = "Clock", Parent = baseSim, StartDate = new DateTime(1998, 11, 9), EndDate = new DateTime(1998, 11, 12) }; MockSummary summary = new MockSummary() { Name = "Summary", Parent = baseSim }; baseSim.Children = new List <Model>() { excelWeather, clock, summary }; MockStorage storage = new MockStorage(); Simulations simsToRun = Simulations.Create(new List <IModel> { baseSim, storage }); IJobManager jobManager = Runner.ForSimulations(simsToRun, simsToRun, false); IJobRunner jobRunner = new JobRunnerSync(); jobRunner.JobCompleted += Utilities.EnsureJobRanGreen; jobRunner.Run(jobManager, true); }
public async Task InitializeSmtpClientAsync_Successful() { MockStorage storage = new MockStorage(); SmtpClientGetter getter = storage.Create(); await getter.InitializeSmtpClientAsync(storage.SmtpConfigMock.Object); Assert.AreSame(getter.Smtp, storage.SmtpClientMock.Object); storage.SmtpClientMock.Verify(a => a.ConnectAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <SecureSocketOptions>(), It.IsAny <CancellationToken>()), Times.Once); storage.SmtpClientMock.Verify(a => a.AuthenticateAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Once); storage.SmtpClientMock.VerifyNoOtherCalls(); }
public PrigTypeMocker(MockStorage ms, ISpecimenBuilder builder) { if (ms == null) { throw new ArgumentNullException("ms"); } if (builder == null) { throw new ArgumentNullException("builder"); } m_ms = ms; m_builder = builder; }
public void _0001() { MockStorage storage = new MockStorage(); var persons = new MockPersonCollection() { new MockPersonItem() { FirstName = "Homer", LastName = "Simpson", Age = 20 }, new MockPersonItem() { FirstName = "Bart", LastName = "Simpson", Age = 20 }, new MockPersonItem() { FirstName = "Lisa", LastName = "Simposn", Age = 25 } }; storage.UniCollection = new UniCollection(); var cars = new MockCarCollection() { new MockCarItem("Suzuki", "Orage"), new MockCarItem("BMW", "Black"), new MockCarItem("Audi", "Green") }; foreach (var item in persons) { storage.UniCollection.Add(item); } foreach (var item in cars) { storage.UniCollection.Add(item); } var pth = @"D:\test.xml"; SaveToFile(pth, storage); var loaded = LoadFromFile(pth); }
public void AutoConfiguredMoqPrigCustomization_should_not_mock_void_method_because_it_makes_no_effects() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Default); var fixture = new Fixture().Customize(new AutoConfiguredMoqPrigCustomization(ms)); PConsole.WriteLineString().Body = value => { throw new NotImplementedException(); }; fixture.Create <PConsole>(); // Act, Assert Assert.Throws <NotImplementedException>(() => Console.WriteLine("bla bla bla")); } }
public void StorageIsUsedByFacadeMethods() { MockStorage storage = new MockStorage(); LogicalThreadContext.SetStorage(storage); object value = new object(); LogicalThreadContext.SetData("key", value); Assert.AreSame( value, storage.data["key"] ); object data = LogicalThreadContext.GetData("key"); Assert.AreSame(value, data); LogicalThreadContext.FreeNamedDataSlot("key"); Assert.IsFalse( storage.data.ContainsKey("key") ); }
public void RestartCurrentProcessWith_should_invoke_additionalSetup() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var procStartInfo = new ProcessStartInfo(); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.StartInfoGet().Body = @this => procStartInfo; curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Expect(_ => _(It.Is<ProcessStartInfo>(x => x.Verb == "runas" )), Times.Once()).Returns(new PProxyProcess()) ); PProcess.GetCurrentProcess().Body = () => curProc; var additionalSetup = ms.Create<Action<ProcessStartInfo>>().Object; Mock.Get(additionalSetup).Setup(_ => _(It.IsAny<ProcessStartInfo>())).Callback(() => procStartInfo.Verb = "runas"); // Act var result = ULProcessMixin.RestartCurrentProcessWith(additionalSetup); // Assert Assert.IsTrue(result); ms.Verify(); } }
public void CallWebService_should_set_HttpWebRequest_to_request_textxml_content() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); // And also, you can verify whether HttpWebRequest is set intendedly if you use Moq. var requestProxy = new PProxyHttpWebRequest(); requestProxy.ContentTypeSetString().BodyBy(ms).Expect(_ => _(requestProxy, "text/xml;charset=\"utf-8\"")); requestProxy.MethodSetString().BodyBy(ms).Expect(_ => _(requestProxy, "GET")); requestProxy.TimeoutSetInt32().BodyBy(ms).Expect(_ => _(requestProxy, 1000)); requestProxy.CredentialsSetICredentials().BodyBy(ms).Expect(_ => _(requestProxy, CredentialCache.DefaultNetworkCredentials)); var responseProxy = new PProxyHttpWebResponse(); responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.OK; requestProxy.GetResponse().Body = @this => responseProxy; var url = "testService"; PWebRequest.CreateString().Body = @this => requestProxy; // Act var actual = new WebServiceClient().CallWebService(url); // Assert Assert.IsTrue(actual); ms.Verify(); } }
public void RestartCurrentProcess_should_return_false_if_user_cancelled_starting_process() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.IsAny<ProcessStartInfo>())).Throws(new Win32Exception(1223)) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act var result = ULProcessMixin.RestartCurrentProcess(); // Assert Assert.IsFalse(result); } }
public void RestartCurrentProcess_should_start_new_process_and_close_current_process() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironment.GetCommandLineArgs().BodyBy(ms).Expect(_ => _(), Times.Once()).Returns(new[] { "file name" }); PEnvironment.CurrentDirectoryGet().BodyBy(ms).Expect(_ => _(), Times.Once()).Returns("current directory"); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms). Customize(m => m. Do(curProcMainMod.FileNameGet).Expect(_ => _(curProcMainMod), Times.Once()).Returns("file path") ); var curProc = new PProxyProcess(); curProc.StartInfoGet().BodyBy(ms).Expect(_ => _(curProc), Times.Once()).Returns(new ProcessStartInfo() { UserName = "******" }); curProc.MainModuleGet().BodyBy(ms).Expect(_ => _(curProc), Times.Once()).Returns(curProcMainMod); curProc.CloseMainWindow().BodyBy(ms).Expect(_ => _(curProc), Times.Once()).Returns(true); PProcess.GetCurrentProcess().BodyBy(ms).Expect(_ => _(), Times.Once()).Returns(curProc); PProcess.StartProcessStartInfo().BodyBy(ms).Expect(_ => _(It.Is<ProcessStartInfo>(x => x.UserName == "urasandesu" && x.UseShellExecute == true && x.WorkingDirectory == "current directory" && x.FileName == "file path" )), Times.Once()).Returns(new PProxyProcess()); // Act var result = ULProcessMixin.RestartCurrentProcess(); // Assert Assert.IsTrue(result); ms.Verify(); } }
public static MockStorage AutoBodyBy(MockStorage ms) { { var m = PEnvironment.GetCommandLineArgs().BodyBy(ms); m.Setup(_ => _()).Returns(new[] { Guid.NewGuid().ToString() }); ms.Set(PEnvironment.GetCommandLineArgs, m); } { var m = PEnvironment.CurrentDirectoryGet().BodyBy(ms); m.Setup(_ => _()).Returns(Guid.NewGuid().ToString()); ms.Set(PEnvironment.CurrentDirectoryGet, m); } return ms; }
public void RestartCurrentProcess_should_throw_exception_as_it_is_except_for_Win32Exception() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.IsAny<ProcessStartInfo>())).Throws(new FileNotFoundException()) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act, Assert Assert.Throws<FileNotFoundException>(() => ULProcessMixin.RestartCurrentProcess()); } }
public static MockStorage AutoBodyBy(MockStorage ms) { { var m = PProcess.GetCurrentProcess().BodyBy(ms); m.Setup(_ => _()).Returns(new PProxyProcess()); ms.Set(PProcess.GetCurrentProcess, m); } { var m = PProcess.StartProcessStartInfo().BodyBy(ms); m.Setup(_ => _(It.IsAny<ProcessStartInfo>())).Returns(new PProxyProcess()); ms.Set(PProcess.StartProcessStartInfo, m); } return ms; }
public void RestartCurrentProcess_should_organize_command_line_arguments_if_they_contain_double_quote() { using (new IndirectionsContext()) { // Arrange var ms = new MockStorage(MockBehavior.Strict); PEnvironmentMixin.AutoBodyBy(ms). Customize(m => m. Do(PEnvironment.GetCommandLineArgs).Setup(_ => _()).Returns(new[] { Guid.NewGuid().ToString(), "a a", "\"b\"bb", "c" }) ); var curProcMainMod = new PProxyProcessModule(); curProcMainMod.AutoBodyBy(ms); var curProc = new PProxyProcess(); curProc.AutoBodyBy(ms); curProc.MainModuleGet().Body = @this => curProcMainMod; PProcessMixin.AutoBodyBy(ms). Customize(m => m. Do(PProcess.StartProcessStartInfo).Setup(_ => _(It.Is<ProcessStartInfo>(x => x.Arguments == "\"a a\" \"\\\"b\\\"bb\" \"c\"" ))).Returns(new PProxyProcess()) ); PProcess.GetCurrentProcess().Body = () => curProc; // Act var result = ULProcessMixin.RestartCurrentProcess(); // Assert Assert.IsTrue(result); } }