Inheritance: MonoBehaviour
        static void Main(string[] args)
        {
            // Original delegate syntax required
              // initialization with a named method.
              TestDelegate testDelA = new TestDelegate(M);

              // C# 2.0: A delegate can be initialized with
              // inline code, called an "anonymous method." This
              // method takes a string as an input parameter.
              TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

              // C# 3.0. A delegate can be initialized with
              // a lambda expression. The lambda also takes a string
              // as an input parameter (x). The type of x is inferred by the compiler.
              TestDelegate testDelC = (x) => { Console.WriteLine(x); };

              // Invoke the delegates.
              testDelA("Hello. My name is M and I write lines.");
              testDelB("That's nothing. I'm anonymous and ");
              testDelC("I'm a famous author.");

              // Initialize delegate with named method, anonymous method and lamba expression.
              TestDelegate testDel = new TestDelegate(M);
              testDel += delegate(string s) { Console.WriteLine(s); };
              testDel += (x) => { Console.WriteLine(x); };

              // Invoke the delegate.
              testDel("Delegate with multiple initialisations.");

              Console.ReadLine(); //wait for <ENTER>
        }
 /// <summary>
 /// Runs a code example in mocked mode.
 /// </summary>
 /// <param name="mockData">The mock data for mocking SOAP request and
 /// responses for API calls.</param>
 /// <param name="exampleDelegate">The delegate that initializes and runs the
 /// code example.</param>
 /// <param name="callback">The callback to be called before mocked responses
 /// are sent. You could use this callback to verify if the request was
 /// serialized correctly.</param>
 /// <remarks>This method is not thread safe, but since NUnit can run tests
 /// only in a single threaded mode, thread safety is not a requirement.
 /// </remarks>
 protected void RunMockedExample(ExamplesMockData mockData, TestDelegate exampleDelegate,
     WebRequestInterceptor.OnBeforeSendResponse callback) {
   TextWriter oldWriter = Console.Out;
   try {
     clientLoginInterceptor.Intercept = true;
     clientLoginInterceptor.RaiseException = false;
     awapiInterceptor.Intercept = true;
     AuthToken.Cache.Clear();
     awapiInterceptor.LoadMessages(mockData.MockMessages,
          delegate(Uri requestUri, WebHeaderCollection headers, String body) {
            VerifySoapHeaders(requestUri, body);
            callback(requestUri, headers, body);
          }
      );
     StringWriter newWriter = new StringWriter();
     Console.SetOut(newWriter);
     AdWordsAppConfig config = (user.Config as AdWordsAppConfig);
     exampleDelegate.Invoke();
     Assert.AreEqual(newWriter.ToString().Trim(), mockData.ExpectedOutput.Trim());
   } finally {
     Console.SetOut(oldWriter);
     clientLoginInterceptor.Intercept = false;
     awapiInterceptor.Intercept = false;
   }
 }
    public void addChildToThingThrowsException()
    {
      Thing thing = new Thing("lantern");

      var testDel = new TestDelegate(() => thing.AddChild(new Thing("fork")));
      Assert.That(testDel, Throws.TypeOf<NoChildrenForThingsException>());
    }
Beispiel #4
0
        public void TestArduinoStateToggles()
        {
            ArduinoCommsBase motorArduino = new MotorControllerArduino(mLogger);
            TestDelegate connectDel = new TestDelegate(delegate() { motorArduino.StartArduinoComms(); });

            Assert.AreEqual(motorArduino.ArduinoState, ProsthesisCore.Telemetry.ProsthesisTelemetry.DeviceState.Uninitialized);
            Assert.DoesNotThrow(connectDel);

            Assert.DoesNotThrow(delegate() { motorArduino.ToggleArduinoState(false); });
            //Wait 100ms for the message to cycle
            System.Threading.Thread.Sleep(100);

            Assert.AreEqual(motorArduino.ArduinoState, ProsthesisCore.Telemetry.ProsthesisTelemetry.DeviceState.Disabled);

            Assert.DoesNotThrow(delegate() { motorArduino.ToggleArduinoState(true); });
            //Wait 100ms for the message to cycle
            System.Threading.Thread.Sleep(100);
            Assert.AreEqual(motorArduino.ArduinoState, ProsthesisCore.Telemetry.ProsthesisTelemetry.DeviceState.Active);

            Assert.IsTrue(motorArduino.IsConnected);

            Assert.DoesNotThrow(delegate() { motorArduino.StopArduinoComms(true); });
            Assert.IsFalse(motorArduino.IsConnected);

            Assert.AreEqual(motorArduino.ArduinoState, ProsthesisCore.Telemetry.ProsthesisTelemetry.DeviceState.Disconnected);
        }
 public void func()
 {
     TestDelegate d1 = new TestDelegate(CallBackOne);
     d1 += new TestDelegate(CallBackTwo);
     cout(d1.Target);
     d1.BeginInvoke(null, null);
 }
    static void Main(string[] args)
    {
        // Original delegate syntax required
                    // initialization with a named method.
                    TestDelegate testDelA = new TestDelegate(M);

                    // C# 2.0: A delegate can be initialized with
                    // inline code, called an "anonymous method." This
                    // method takes a string as an input parameter.
                    TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

                    // C# 3.0. A delegate can be initialized with
                    // a lambda expression. The lambda also takes a string
                    // as an input parameter (x). The type of x is inferred by the compiler.
                    TestDelegate testDelC = (x) => { Console.WriteLine(x); };

                    // Invoke the delegates.
                    testDelA("Hello. My name is M and I write lines.");
                    testDelB("That's nothing. I'm anonymous and ");
                    testDelC("I'm a famous author.");

                    // Keep console window open in debug mode.
                    Console.WriteLine("Press any key to exit.");
                    Console.ReadKey();
    }
Beispiel #7
0
 public static ArgumentOutOfRangeException CatchArgumentOutOfRangeException(TestDelegate code, string paramName, string exceptionMessage, params object[] args)
 {
     var exception = Assert.Catch<ArgumentOutOfRangeException>(code);
     Assert.AreEqual(paramName, exception.ParamName);
     Assert.AreEqual(GetMessage(paramName, exceptionMessage, args), exception.Message);
     return exception;
 }
        public void Repricing_InvalidTickets_ExceptionThrown()
        {
            var order = new Order();
            var callDelegate = new TestDelegate(() => _pricingManager.RepricingAsync(order).Wait());

            Assert.Throws<AggregateException>(callDelegate);
            Assert.Throws<AggregateException>(callDelegate).InnerExceptions.Any(exception => exception is TicketNotValidException);
        }
Beispiel #9
0
        public void When_User_Id_Is_Not_Provided_It_Must_Throws_Exception()
        {
            TestDelegate createUserWithNullableId = new TestDelegate(() => { new User(null); });
            TestDelegate createUserWithEmptyId = new TestDelegate(() => { new User(String.Empty); });

            Assert.Throws<ArgumentNullException>(createUserWithNullableId, "User ID cannot be null.");
            Assert.Throws<ArgumentException>(createUserWithEmptyId, "User ID cannot be empty.");
        }
 void Start()
 {
     //use default when not be set value in Awake
     if (testDelegate == null)
         testDelegate = nullTestDelegate;
     if (setByfunction == null)
         setByfunction = nullTestDelegate;
 }
 public void GetParameters()
 {
     StringWriter sw = new StringWriter();
     string name = "MyName";
     Delegate hello = new TestDelegate(this.Hello);
     TestCase tc = new TestCase(name, hello, sw);
     ArrayAssert.AreEqual(new Object[] { sw }, tc.GetParameters());
 }
 public void GetTest()
 {
     StringWriter sw = new StringWriter();
     string name = "MyName";
     Delegate hello = new TestDelegate(this.Hello);
     TestCase tc = new TestCase(name, hello, sw);
     Assert.AreEqual(hello.Method, tc.TestDelegate.Method);
 }
        public void when_balance_below_0_trader_should_go_bankrupt()
        {
            _trader.SetBalance(0);

            var methodUnderTest = new TestDelegate(_trader.CheckBankrupt);

            Assert.Throws<ApplicationException>(methodUnderTest);
        }
Beispiel #14
0
 public static void Execute() {
     TestDelegate d1 = new TestDelegate(Dowork);
     TestDelegate d2 = delegate(string s) { Console.WriteLine(s); };
     TestDelegate d3 = (x) => { Console.WriteLine(x); };
     d1("Hello World");
     d2("Hello World2");
     d3("Hello World3");
     TestLambda((x) => { Console.WriteLine(x); });
 }
    public void ObjectWithBothMaleAndNeutralAttributesThrows()
    {
      var parser = new Parser();
      

      var testDel = new TestDelegate(() => parser.Parse("Jason [mp]"));
      Assert.That(testDel, Throws.TypeOf<PersonCannotBeTwoGenders>());

    }
 public void Invoke()
 {
     StringWriter sw = new StringWriter();
     string name = "MyName";
     Delegate hello = new TestDelegate(this.Hello);
     TestCase tc = new TestCase(name, hello, sw);
     tc.Invoke(this,new ArrayList());
     Assert.AreEqual("hello", sw.ToString());
 }
        public void GetConfigurationBeforeLoadingConfigurationMethods()
        {
            // Arrange
            // Action
            var testCase = new TestDelegate(() => Configure.Get<IMyTestConfiguration>());

            // Assert
            Assert.Throws(typeof(ConfigurationEnvironmentNotInitializedException), testCase);
        }
Beispiel #18
0
        public static void Argument(TestDelegate code, string message, string paramName)
        {
            var constraint =
                Throws.ArgumentException
                    .With.Message.StartsWith(message)
                    .And
                    .With.Property("ParamName").EqualTo(paramName);

            Assert.That(code, constraint);
        }
 /// <summary>
 /// Validates whether an ArgumentNullException is called whenever a required
 /// property in targetObject is null, and testDelegate is invoked.
 /// </summary>
 /// <param name="targetObject">The target object.</param>
 /// <param name="propertyNames">The property names to be checked for null
 /// values.</param>
 /// <param name="testDelegate">The test delegate.</param>
 public static void ValidateRequiredParameters(object targetObject, string[] propertyNames,
     TestDelegate testDelegate) {
   foreach (string propertyName in propertyNames) {
     PropertyInfo propInfo = targetObject.GetType().GetProperty(propertyName);
     object oldValue = propInfo.GetValue(targetObject, null);
     propInfo.SetValue(targetObject, null, null);
     Assert.Throws<ArgumentNullException>(testDelegate);
     propInfo.SetValue(targetObject, oldValue, null);
   }
 }
Beispiel #20
0
 public void CircularReferenceTesting2(ContextValue[] values)
 {
     TestDelegate handle = new TestDelegate(() => {
         ExecutionContext context = new ExecutionContext(Parser.GetParser());
         foreach (ContextValue value in values) {
             context.Set(value);
         }
         context.GetValue("a", null);
     });
     Assert.Throws<CircularReferenceException>(handle);
 }
        static void AssertMethodFailsWithSerializableException(TestDelegate intentionallyFailingMethod)
        {
            var original = Assert.Catch<Exception>(intentionallyFailingMethod);

            var formatter = new BinaryFormatter();
            var ms = new MemoryStream();
            formatter.Serialize(ms, original);
            object deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray()));

            Assert.AreEqual(original.ToString(), deserialized.ToString());
        }
Beispiel #22
0
 static void Main(string[] args)
 {
     //Creating an instance of the delegate and calling it
     TestDelegate td = new TestDelegate(Program.Method);
     Console.WriteLine(td("Kuntal"));
     //Following are the different ways of calling and passing a delegate
     TestDelegate((str) => str + "kkk");
     TestDelegate(Program.Method);
     TestDelegate(td);
     Console.ReadKey();
 }
Beispiel #23
0
 /// <summary>
 /// Capture any exception that is thrown by the delegate
 /// </summary>
 /// <param name="code">A TestDelegate</param>
 /// <returns>The exception thrown, or null</returns>
 public static Exception Exception(TestDelegate code)
 {
     try
     {
         code();
         return null;
     }
     catch (Exception ex)
     {
         return ex;
     }
 }
        public void ItShouldThrowExceptionIfConnectionStringDoesNotExistWhenCreatingDatabase()
        {
            // Arrange
            Database databaseContext;
            TestDelegate databaseContextInitializer;

            // Act
            databaseContextInitializer = new TestDelegate(() => databaseContext = Database.ForConnectionString("NonExistentConnection"));
            
            // Assert
            Assert.That(databaseContextInitializer, Throws.Exception);
        }
Beispiel #25
0
 private bool BeginTestcase(TestDelegate test)
 {
     if (test())
     {
         _numTestcases++;
         return true;
     }
     else
     {
         _numErrors++;
         return false;
     }
 }
Beispiel #26
0
 static void Main(string[] args)
 {
     Printer t = new Printer();
     Match m = new Match();
     //创建委托对象
     TestDelegate d1 = new TestDelegate(m.MaxNum);
     d1 += new TestDelegate(m.MinNum);
     TestDelegate d2 = new TestDelegate(m.MinNum);
     //将委托作为参数传给方法
     t.PrintInt(d1);
     t.PrintInt(d2);
     Console.Read();
 }
Beispiel #27
0
        static void Main(string[] args)
        {
            //-- Instantiate the delegate
            TestDelegate t = new TestDelegate(Display);

            //-- Input some text
            Console.WriteLine("Please enter a string:");
            string message = Console.ReadLine();

            //-- Invoke the delegate
            t(message);
            Console.ReadLine();
        }
Beispiel #28
0
        public static bool AssertThisDelegateCausesArgumentException(TestDelegate d)
        {
            try
            {
                d();
            }
            catch(ArgumentException)
            {
                return true;
            }

            return false;
        }
Beispiel #29
0
        public static void Fails(TestDelegate action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            Assert.That(() => {}, Throws.Exception);
        }
        public void ConfigureExplicitlyWithMultipleValidConfigurationProvidersAndOneInvalidProvider()
        {
            // Arrange
            Configure.TheEnvironment.AddConfigurationMethod<GoodMockConfigurationMethodProvider>();
            Configure.TheEnvironment.AddConfigurationMethod<GoodMockConfigurationMethodProvider2>();

            // Action
            var testDelegate = new TestDelegate(() =>
                {
                    Configure.TheEnvironment.AddConfigurationMethod<BadMockConfigurationMethodProvider2>();
                });

            // Assert
            Assert.Throws<ProviderMustSupportAtLeastOneConfigureAttributeType>(testDelegate);
        }
Beispiel #31
0
        public void UpdateStructuresWithImportedData_ImportedDataContainsDuplicateIds_ThrowsUpdateDataException()
        {
            // Setup
            const string duplicateId = "I am a duplicate id";

            HeightStructure[] importedHeightStructures =
            {
                new TestHeightStructure(duplicateId, "name"),
                new TestHeightStructure(duplicateId, "Other name")
            };

            var strategy = new HeightStructureReplaceDataStrategy(new HeightStructuresFailureMechanism());

            // Call
            TestDelegate call = () => strategy.UpdateStructuresWithImportedData(importedHeightStructures,
                                                                                sourceFilePath);

            // Assert
            var    exception       = Assert.Throws <UpdateDataException>(call);
            string expectedMessage = "Kunstwerken moeten een unieke id hebben. " +
                                     $"Gevonden dubbele elementen: {duplicateId}.";

            Assert.AreEqual(expectedMessage, exception.Message);
        }
        public void ReadFailureMechanismSection_FileHadMultiPolylines_ThrowCriticalFileReadException()
        {
            // Setup
            string validFilePath = TestHelper.GetTestDataPath(TestDataPath.Riskeer.Common.IO,
                                                              Path.Combine("FailureMechanismSections", "Artificial_MultiPolyline_vakken.shp"));

            using (var reader = new FailureMechanismSectionReader(validFilePath))
            {
                // Call
                TestDelegate call = () =>
                {
                    reader.ReadFailureMechanismSection();
                    reader.ReadFailureMechanismSection();
                    reader.ReadFailureMechanismSection();
                    reader.ReadFailureMechanismSection();
                };

                // Assert
                string message         = Assert.Throws <CriticalFileReadException>(call).Message;
                string expectedMessage = $"Fout bij het lezen van bestand '{validFilePath}': het bestand bevat een of meerdere multi-polylijnen. " +
                                         "Multi-polylijnen worden niet ondersteund.";
                Assert.AreEqual(expectedMessage, message);
            }
        }
        public void Reproduction3()
        {
            TestDelegate act = () =>
            {
                // Given
                using (var transaction = new TransactionScope())
                {
                    // When
                    ExecuteSql("INSERT Logs VALUES(1)");
                    try { ExecuteSql("INSERT Logs VALUES('oops')"); } catch (Exception) { }
                    ExecuteSql("INSERT Logs VALUES(2)");
                    ExecuteSql("INSERT Logs VALUES(3)");
                    transaction.Complete();
                }
            };

            // Then
            Assert.Multiple(() =>
            {
                Assert.That(act, Throws.Nothing);
                Assert.That(GetLogs(), Is.EquivalentTo(new[] { 1, 2, 3 }));
            });
            // https://stackoverflow.com/a/5623877/1400547
        }
Beispiel #34
0
        public static void Calculate_AbortedTakeOffDistanceCalculatorThrowsCalculatorException_ThrowsCalculatorException()
        {
            // Setup
            var random = new Random(21);

            AircraftData        aircraftData              = AircraftDataTestFactory.CreateRandomAircraftData();
            var                 integrator                = Substitute.For <IIntegrator>();
            int                 nrOfFailedEngines         = random.Next();
            double              density                   = random.NextDouble();
            double              gravitationalAcceleration = random.NextDouble();
            CalculationSettings calculationSettings       = CalculationSettingsTestFactory.CreateDistanceCalculatorSettings();

            var calculatorException = new CalculatorException();
            var abortedTakeOffDistanceCalculator = Substitute.For <IDistanceCalculator>();

            abortedTakeOffDistanceCalculator.Calculate().Throws(calculatorException);

            var continuedTakeOffDistanceCalculator = Substitute.For <IDistanceCalculator>();
            var continuedTakeOffDistanceOutput     = new DistanceCalculatorOutput(calculationSettings.FailureSpeed, random.NextDouble());

            continuedTakeOffDistanceCalculator.Calculate().Returns(continuedTakeOffDistanceOutput);

            var distanceCalculatorFactory = Substitute.For <IDistanceCalculatorFactory>();

            distanceCalculatorFactory.CreateAbortedTakeOffDistanceCalculator(null, null, 0, 0, null).ReturnsForAnyArgs(abortedTakeOffDistanceCalculator);

            var aggregatedCalculator = new Calculator.AggregatedDistanceCalculator.AggregatedDistanceCalculator(distanceCalculatorFactory);

            // Call
            TestDelegate call = () => aggregatedCalculator.Calculate(aircraftData, integrator, nrOfFailedEngines, density, gravitationalAcceleration, calculationSettings);

            // Assert
            var exception = Assert.Throws <CalculatorException>(call);

            Assert.AreSame(calculatorException, exception);
        }
Beispiel #35
0
        public void Mean_ReadOnlyWithObserverable_ThrowsArgumentException()
        {
            // Setup
            var mocks        = new MockRepository();
            var distribution = mocks.Stub <IVariationCoefficientDistribution>();
            var handler      = mocks.Stub <IObservablePropertyChangeHandler>();

            mocks.ReplayAll();

            var properties = new SimpleDistributionProperties(
                VariationCoefficientDistributionReadOnlyProperties.All,
                distribution,
                handler);

            // Call
            TestDelegate test = () => properties.Mean = new RoundedDouble(2, 20);

            // Assert
            const string expectedMessage = "Mean is set to be read-only.";
            string       actualMessage   = Assert.Throws <InvalidOperationException>(test).Message;

            Assert.AreEqual(expectedMessage, actualMessage);
            mocks.VerifyAll();
        }
Beispiel #36
0
        public void TestSequence()
        {
            //CommandWithInjection requires an ISimpleInterface
            injectionBinder.Bind <ISimpleInterface>().To <SimpleInterfaceImplementer>().ToSingleton();

            //Bind the trigger to the command
            commandBinder.Bind <NoArgSignal>().To <CommandWithInjection>().To <CommandWithExecute>().To <CommandThatThrows>().InSequence();

            TestDelegate testDelegate = delegate
            {
                NoArgSignal signal = injectionBinder.GetInstance <NoArgSignal>() as NoArgSignal;
                signal.Dispatch();
            };

            //That the exception is thrown demonstrates that the last command ran
            NotImplementedException ex = Assert.Throws <NotImplementedException>(testDelegate);

            Assert.NotNull(ex);

            //That the value is 100 demonstrates that the first command ran
            ISimpleInterface instance = injectionBinder.GetInstance <ISimpleInterface>() as ISimpleInterface;

            Assert.AreEqual(100, instance.intValue);
        }
Beispiel #37
0
        public void Reproject_ForLinearRingWithTargetProjectionNull_ThrowArgumentNullException()
        {
            // Setup
            var p1 = new Coordinate(0.0, 0.0);
            var p2 = new Coordinate(1.1, 1.1);

            var linearRing = new LinearRing(new[]
            {
                p1,
                p2,
                p2,
                p1
            });

            ProjectionInfo projection = KnownCoordinateSystems.Projected.NationalGrids.Rijksdriehoekstelsel;

            // Call
            TestDelegate call = () => linearRing.Reproject(projection, null);

            // Assert
            string paramName = Assert.Throws <ArgumentNullException>(call).ParamName;

            Assert.AreEqual("target", paramName);
        }
Beispiel #38
0
        public void TestGetMediaFromInvalidImageReturnsError()
        {
            var options = new MediaOptionsBuilder().Set
                          .Height(100)
                          .Build();

            var request = ItemWebApiRequestBuilder.DownloadResourceRequestWithMediaPath("/sitecore/media library/Images/nexus")
                          .DownloadOptions(options)
                          .Build();

            TestDelegate testCode = async() =>
            {
                var   task = this.session.DownloadMediaResourceAsync(request);
                await task;
            };
            Exception exception = Assert.Throws <LoadDataFromNetworkException>(testCode);

            Assert.IsTrue(exception.Message.Contains("Unable to download data from the internet"));
            Assert.AreEqual("System.Net.Http.HttpRequestException", exception.InnerException.GetType().ToString());

            // Windows : "Response status code does not indicate success: 404 (Not Found)"
            // iOS     : "404 (Not Found)"
            Assert.IsTrue(exception.InnerException.Message.Contains("Not Found"));
        }
Beispiel #39
0
        public void AssertExceptionThrown <T>(TestDelegate method) where T : System.Exception
        {
            try {
                method.DynamicInvoke(null);
            } catch (System.Reflection.TargetInvocationException e) {
                if (e.InnerException.GetType().Equals(typeof(T)))
                {
                    TestResult res = passed();
                    res.expected = typeof(T).ToString();
                }
                else
                {
                    TestResult res = failed();
                    res.expected = typeof(T).ToString();
                    res.received = e.InnerException.ToString();
                }
                return;
            }

            TestResult res2 = failed();

            res2.expected = typeof(T).ToString();
            res2.received = "no exception";
        }
        public void Invoke_WhenHostIsNotSetted_ShouldThrowException()
        {
            // Arrange
            var requestDelegate = fixture.Create <RequestDelegate>();
            var httpClientMock  = fixture.Freeze <Mock <IProxyHttpClient> >();

            var options = CreateProxyOptions();

            options.Host = null;

            optionsMock.Setup(x => x.Value).Returns(options);

            httpClientFactoryMock.Setup(x => x.Create(HttpClientType.HttpClient))
            .Returns(httpClientMock.Object);

            TestDelegate action = () => new ProxyServerMiddleware(httpClientFactoryMock.Object, requestDelegate, optionsMock.Object);

            // Action

            // Assets
            var exception = Assert.Throws <ArgumentException>(action);

            Assert.AreEqual("Host is undefined", exception.Message);
        }
        public async void UploadImageToNotExistentFolder()
        {
            await this.RemoveAll();

            using (var image = GetStreamFromUrl(TestEnvironment.Images.Gif.Pictures_2))
            {
                var request = ItemWebApiRequestBuilder.UploadResourceRequestWithParentPath("/not existent/folder")
                              .ItemDataStream(image)
                              .ItemName("test")
                              .FileName("test.png")
                              .Build();

                TestDelegate testCode = async() =>
                {
                    var   task = this.session.UploadMediaResourceAsync(request);
                    await task;
                };

                Exception exception = Assert.Throws <ParserException>(testCode);
                Assert.AreEqual("[Sitecore Mobile SDK] Data from the internet has unexpected format", exception.Message);
                Assert.AreEqual("Sitecore.MobileSDK.API.Exceptions.WebApiJsonErrorException", exception.InnerException.GetType().ToString());
                Assert.AreEqual("The specified location not found.", exception.InnerException.Message);
            }
        }
Beispiel #42
0
        public void GetTile_TileFetcherDisposed_ThrowObjectDisposedException()
        {
            // Setup
            var mocks        = new MockRepository();
            var tileProvider = mocks.Stub <ITileProvider>();

            mocks.ReplayAll();

            var tileFetcher = new AsyncTileFetcher(tileProvider, 1, 2);

            tileFetcher.Dispose();

            var tileInfo = new TileInfo();

            // Call
            TestDelegate call = () => tileFetcher.GetTile(tileInfo);

            // Assert
            string objectName = Assert.Throws <ObjectDisposedException>(call).ObjectName;

            Assert.AreEqual("AsyncTileFetcher", objectName);

            mocks.VerifyAll();
        }
Beispiel #43
0
        public void AddCategory_OverlappedSKU_Fail()
        {
            // Arrange
            var categoryService = new CategoryService(_categoryRepositoryMock.Object);
            var categoryDTO     = new CategoryDTO()
            {
                Name          = "Category 1",
                CanBeFeatured = true,
                SKUStart      = 10000,
                SKUEnd        = 20000
            };
            var fakeCategory = new Category(categoryDTO.Name, categoryDTO.SKUStart, categoryDTO.SKUEnd, categoryDTO.CanBeFeatured);

            _categoryRepositoryMock.Setup(a => a.GetCategories(It.IsAny <ISpecification <Category> >()))
            .Returns(FakeCategories());
            _categoryRepositoryMock.Setup(a => a.AddCategory(It.IsAny <Category>()))
            .Returns(fakeCategory);

            // Act
            TestDelegate result = () => categoryService.AddCategory(categoryDTO);

            // Assert
            Assert.Throws <MMTException>(result, "Overlapped categories");
        }
Beispiel #44
0
        public void Delete_WithValidId_ExpectInvalidOperationException(
            string xmlDataFilename,
            int studentId)
        {
            // Arrange
            TestFixtureContext.SetupTestDatabase(xmlDataFilename);

            var entity = TestFixtureContext.CreateValidEntity(studentId);

            var classUnderTest = TestFixtureContext.CreateInstance();

            // Act
            classUnderTest.Delete(entity);

            // Assert
            TestDelegate retrieve =
                () =>
                TestFixtureContext.Retrieve <string>(
                    "HighSchoolName",
                    "Student",
                    string.Format("[Id] = {0}", studentId));

            Assert.Throws <InvalidOperationException>(retrieve);
        }
        public void ReplaceData_ImportedDataCollectionContainsDuplicateItems_ThrowsUpdateDataException()
        {
            // Setup
            var collection = new TestUniqueItemCollection();
            var strategy   = new ConcreteStrategyClass(new TestFailureMechanism(), collection);

            const string duplicateName = "Item A";
            var          itemsToAdd    = new[]
            {
                new TestItem(duplicateName),
                new TestItem(duplicateName)
            };

            // Call
            TestDelegate call = () => strategy.ConcreteReplaceData(itemsToAdd, "some/source");

            // Assert
            CollectionAssert.IsEmpty(collection);
            var    exception       = Assert.Throws <UpdateDataException>(call);
            string expectedMessage = $"TestItem moeten een unieke naam hebben. Gevonden dubbele elementen: {duplicateName}.";

            Assert.AreEqual(expectedMessage, exception.Message);
            Assert.IsInstanceOf <ArgumentException>(exception.InnerException);
        }
Beispiel #46
0
    public bool ExceptionTest(int id, string msg, Type ehType, TestDelegate d)
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest" + id + ": " + msg);

        try
        {
            retVal = d();

            TestLibrary.TestFramework.LogError("10" + id, "Function should have thrown: " + ehType);
            retVal = false;
        }
        catch (Exception e)
        {
            if (ehType != e.GetType())
            {
                TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
                retVal = false;
            }
        }

        return(retVal);
    }
Beispiel #47
0
        public async Task InsertBulkTestDataAndForceAnException(int integerStandard, string stringStandard, long longStandard, int?integerNullable, long?longNullable)
        {
            ICollection <ChangeLog <int> > changeLogs = new LinkedList <ChangeLog <int> >();

            for (int i = 0; i < 100; i++)
            {
                var changeLog = new ChangeLog <int>()
                {
                    ChangeLogId        = null,
                    ChangedBy          = null,
                    ObjectId           = null,
                    Property           = "integerStandard",
                    ChangedUtc         = DateTime.UtcNow,
                    Value              = integerStandard.ToString(),
                    FullTypeName       = "JSCloud.LogPlayer.Tests.SimpleItem2 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
                    PropertySystemType = "System.Int32"
                };
                changeLogs.Add(changeLog);
            }

            if (Store is MicrosoftSqlStore <int> || Store is LogApplyerIntegrationInMemoryStoreWithSqlBaseStore)
            {
                TestDelegate testDelegate = () => this.Store.StoreAsync(changeLogs).GetAwaiter().GetResult();
                Assert.That(testDelegate, Throws.TypeOf <InvalidOperationException>());

                testDelegate = () => this.Store.StoreAsync(changeLogs.ElementAt(0)).GetAwaiter().GetResult();
                Assert.That(testDelegate, Throws.TypeOf <Exception>());

                changeLogs.ElementAt(0).ChangeLogId = Guid.NewGuid();
                testDelegate = () => this.Store.StoreAsync(changeLogs.ElementAt(0)).GetAwaiter().GetResult();
                Assert.That(testDelegate, Throws.TypeOf <ArgumentException>());

                testDelegate = () => this.Store.StoreAsync(changeLogs).GetAwaiter().GetResult();
                Assert.That(testDelegate, Throws.TypeOf <System.ArgumentException>());
            }
        }
Beispiel #48
0
        public void UpdateSurfaceLinesWithImportedData_ImportedDataContainsDuplicateNames_ThrowsUpdateDataException()
        {
            // Setup
            const string duplicateName = "Duplicate name it is";

            PipingSurfaceLine[] importedSurfaceLines =
            {
                new PipingSurfaceLine(duplicateName),
                new PipingSurfaceLine(duplicateName)
            };

            var strategy = new PipingSurfaceLineReplaceDataStrategy(new PipingFailureMechanism());

            // Call
            TestDelegate call = () => strategy.UpdateSurfaceLinesWithImportedData(importedSurfaceLines,
                                                                                  sourceFilePath);

            // Assert
            var    exception       = Assert.Throws <UpdateDataException>(call);
            string expectedMessage = "Profielschematisaties moeten een unieke naam hebben. " +
                                     $"Gevonden dubbele elementen: {duplicateName}.";

            Assert.AreEqual(expectedMessage, exception.Message);
        }
Beispiel #49
0
        public void Constructor_StochastNamesNotUnique_ThrowArgumentException()
        {
            // Setup
            var random    = new Random(21);
            var stochasts = new[]
            {
                new Stochast("unique", random.NextDouble(), random.NextDouble()),
                new Stochast("non-unique", random.NextDouble(), random.NextDouble()),
                new Stochast("non-unique", random.NextDouble(), random.NextDouble()),
                new Stochast("nonunique", random.NextDouble(), random.NextDouble()),
                new Stochast("nonunique", random.NextDouble(), random.NextDouble())
            };

            // Call
            TestDelegate test = () => new FaultTreeIllustrationPoint("Point A",
                                                                     random.NextDouble(),
                                                                     stochasts,
                                                                     CombinationType.And);

            // Assert
            const string expectedMessage = "Een of meerdere stochasten hebben dezelfde naam.";

            TestHelper.AssertThrowsArgumentExceptionAndTestMessage <ArgumentException>(test, expectedMessage);
        }
        public void Constructor_InvalidCalculatedProbability_ThrowsArgumentOutOfRangeException([Values(-0.01, 1.01)] double calculatedProbability,
                                                                                               [Values(true, false)] bool withIllustrationPoints)
        {
            // Setup
            var random = new Random(32);
            TestGeneralResultSubMechanismIllustrationPoint generalResult = withIllustrationPoints
                                                                               ? new TestGeneralResultSubMechanismIllustrationPoint()
                                                                               : null;

            // Call
            TestDelegate call = () => new HydraulicBoundaryLocationCalculationOutput(random.NextDouble(),
                                                                                     random.NextDouble(),
                                                                                     random.NextDouble(),
                                                                                     calculatedProbability,
                                                                                     random.NextDouble(),
                                                                                     random.NextEnumValue <CalculationConvergence>(),
                                                                                     generalResult);

            // Assert
            var exception = Assert.Throws <ArgumentOutOfRangeException>(call);

            Assert.AreEqual("calculatedProbability", exception.ParamName);
            StringAssert.Contains("Kans moet in het bereik [0,0, 1,0] liggen.", exception.Message);
        }
        public void TestGetItemWithNotExistentUserReturnsError()
        {
            using
            (
                var session = SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(testData.InstanceUrl)
                              .Credentials(this.testData.Users.NotExistent)
                              .DefaultDatabase("web")
                              .DefaultLanguage("en")
                              .Site(testData.ShellSite)
                              .BuildSession()
            )
            {
                TestDelegate testCode = async() =>
                {
                    var   task = session.ReadItemAsync(this.requestWithItemId);
                    await task;
                };
                Exception exception = Assert.Throws <ParserException>(testCode);

                Assert.AreEqual("[Sitecore Mobile SDK] Data from the internet has unexpected format", exception.Message);
                Assert.AreEqual("Sitecore.MobileSDK.API.Exceptions.WebApiJsonErrorException", exception.InnerException.GetType().ToString());
                Assert.True(exception.InnerException.Message.Contains("Access to site is not granted."));
            }
        }
Beispiel #52
0
        public void IsSurfaceLineIntersectionWithReferenceLineInSection_EmptySegmentCollection_ThrowsInvalidOperationException()
        {
            // Setup
            var surfaceLine = new MacroStabilityInwardsSurfaceLine(string.Empty)
            {
                ReferenceLineIntersectionWorldPoint = new Point2D(0.0, 0.0)
            };

            surfaceLine.SetGeometry(new[]
            {
                new Point3D(0.0, 5.0, 0.0),
                new Point3D(0.0, 0.0, 1.0),
                new Point3D(0.0, -5.0, 0.0)
            });
            var referenceLine = new ReferenceLine();

            referenceLine.SetGeometry(new[]
            {
                new Point2D(0.0, 0.0),
                new Point2D(10.0, 0.0)
            });

            var calculation = new MacroStabilityInwardsCalculationScenario
            {
                InputParameters =
                {
                    SurfaceLine = surfaceLine
                }
            };

            // Call
            TestDelegate call = () => calculation.IsSurfaceLineIntersectionWithReferenceLineInSection(Enumerable.Empty <Segment2D>());

            // Assert
            Assert.Throws <InvalidOperationException>(call);
        }
Beispiel #53
0
    public static void Run(TestDelegate renderCallback)
    {
        if (m_Instance == null)
        {
            m_Instance = ScriptableObject.CreateInstance <RenderLoopTestFixture>();
        }

        var sceneCamera = Camera.main;
        var camObject   = sceneCamera.gameObject;

        GraphicsSettings.renderPipelineAsset = m_Instance;
        s_Callback = renderCallback;
        Transform t = camObject.transform;

        // Can't use AlignViewToObject because it animates over time, and we want the first frame
        float size    = SceneView.lastActiveSceneView.size;
        float fov     = 90; // hardcoded in SceneView
        float camDist = size / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);

        SceneView.lastActiveSceneView.LookAtDirect(t.position + t.forward * camDist, t.rotation, size);

        sceneCamera.Render();
        GraphicsSettings.renderPipelineAsset = null;
    }
Beispiel #54
0
        /// <summary>
        /// Verifies that a delegate throws a particular exception when called.
        /// </summary>
        /// <param name="expression">A constraint to be satisfied by the exception</param>
        /// <param name="code">A TestSnippet delegate</param>
        /// <param name="message">The message that will be displayed on failure</param>
        /// <param name="args">Arguments to be used in formatting the message</param>
        public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, params object[] args)
        {
            Exception caughtException = null;

#if NET_4_0 || NET_4_5 || PORTABLE
            if (AsyncInvocationRegion.IsAsyncOperation(code))
            {
                using (var region = AsyncInvocationRegion.Create(code))
                {
                    code();

                    try
                    {
                        region.WaitForPendingOperationsToComplete(null);
                    }
                    catch (Exception e)
                    {
                        caughtException = e;
                    }
                }
            }
            else
#endif
            try
            {
                code();
            }
            catch (Exception ex)
            {
                caughtException = ex;
            }

            Assert.That(caughtException, expression, message, args);

            return(caughtException);
        }
Beispiel #55
0
        public void SetCharacteristicPoints_CharacteristicPointsNull_ThrowsImportedDataTransformException()
        {
            // Setup
            const string name        = "Some line name";
            var          surfaceLine = new MacroStabilityInwardsSurfaceLine(name);

            surfaceLine.SetGeometry(new[]
            {
                new Point3D(3, 2, 5),
                new Point3D(3.4, 3, 8),
                new Point3D(4.4, 6, 8),
                new Point3D(5.1, 6, 6.5),
                new Point3D(8.5, 7.2, 4.2),
                new Point3D(9.6, 7.5, 3.9)
            });

            // Call
            TestDelegate test = () => surfaceLine.SetCharacteristicPoints(null);

            // Assert
            var exception = Assert.Throws <ImportedDataTransformException>(test);

            Assert.AreEqual($"Karakteristieke punten definitie voor profielschematisatie '{name}' is verplicht.", exception.Message);
        }
Beispiel #56
0
        public void TestWriteFeatureCollectionWithFirstFeatureGeometryNull()
        {
            // Setup
            var geoJsonWriter = new GeoJsonWriter();

            var featureJson            = "{\"type\": \"Feature\",\"geometry\": {\"type\": \"LineString\",\"coordinates\": [[0,0],[2,2],[3,2]]},\"properties\": {\"key\": \"value\"}}";
            var notNullGeometryFeature = new GeoJsonReader().Read <Feature>(featureJson);

            var attributesTable = new AttributesTable {
                { "key", "value" }
            };
            IGeometry geometry            = null;
            var       nullGeometryFeature = new Feature(geometry, attributesTable);

            var features_notNullFirst = new Collection <IFeature>
            {
                notNullGeometryFeature,
                nullGeometryFeature
            };

            var features_nullFirst = new Collection <IFeature>
            {
                nullGeometryFeature,
                notNullGeometryFeature
            };

            var featureCollection_notNullFirst = new FeatureCollection(features_notNullFirst);
            var featureCollection_nullFirst    = new FeatureCollection(features_nullFirst);

            // Act
            TestDelegate write_notNullFirst = () => geoJsonWriter.Write(featureCollection_notNullFirst);
            TestDelegate write_nullFirst    = () => geoJsonWriter.Write(featureCollection_nullFirst);

            Assert.That(write_notNullFirst, Throws.Nothing);
            Assert.That(write_nullFirst, Throws.Nothing);
        }
Beispiel #57
0
        /*----------------------------------------------------------------------------
        *       %%Function: TestReadLineWithStreamEndingBeforeFileLimit
        *       %%Qualified: TCore.StreamEx.BufferedStreamEx.TestReadLineWithStreamEndingBeforeFileLimit
        *       %%Contact: rlittle
        *
        *   Add characters to the end of the physical file that should not be
        *   visible to the buffer.
        *  ----------------------------------------------------------------------------*/
        public static void TestReadLineWithStreamEndingBeforeFileLimit(string sDebugStream, long ibStart, long ibLim, long lcbSwapBuffer, string[] rgsExpected, long ibSeekExpected, string sExpectedException)
        {
            DebugStream      stm  = DebugStream.StmCreateFromString(sDebugStream + "aaaa\n");
            BufferedStreamEx stmx = new BufferedStreamEx(stm, ibStart, ibLim, lcbSwapBuffer);
            TestDelegate     t    = () =>
            {
                foreach (string s in rgsExpected)
                {
                    Assert.AreEqual(s, stmx.ReadLine());
                }

                Assert.AreEqual(null, stmx.ReadLine());
                Assert.AreEqual(ibSeekExpected, stmx.Position());
            };

            if (sExpectedException != null)
            {
                RunTestExpectingException(t, sExpectedException);
            }
            else
            {
                t();
            }
        }
Beispiel #58
0
        public void Constructor_MigrationFilePathNull_ThrowArgumentException()
        {
            // Setup
            var mocks           = new MockRepository();
            var projectOwner    = mocks.Stub <IProjectOwner>();
            var projectFactory  = mocks.Stub <IProjectFactory>();
            var projectStorage  = mocks.Stub <IStoreProject>();
            var projectMigrator = mocks.Stub <IMigrateProject>();

            mocks.ReplayAll();

            var openProjectProperties = new OpenProjectActivity.OpenProjectConstructionProperties
            {
                FilePath       = "",
                ProjectOwner   = projectOwner,
                ProjectFactory = projectFactory,
                ProjectStorage = projectStorage
            };

            var migrateProjectProperties = new OpenProjectActivity.ProjectMigrationConstructionProperties
            {
                MigrationFilePath = null,
                Migrator          = projectMigrator
            };

            // Call
            TestDelegate call = () => new OpenProjectActivity(openProjectProperties, migrateProjectProperties);

            // Assert
            const string expectedMessage = "Migration target file path should be set.";
            string       paramName       = TestHelper.AssertThrowsArgumentExceptionAndTestMessage <ArgumentException>(call, expectedMessage).ParamName;

            Assert.AreEqual("optionalProjectMigrationProperties", paramName);

            mocks.VerifyAll();
        }
            private static IEnumerable GetCasesForArgumentChecking(string path)
            {
                var          fileSystem            = new MockFileSystem();
                var          fileContentEnumerable = new List <string>();
                var          fileContentArray      = fileContentEnumerable.ToArray();
                TestDelegate writeEnumberable      = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable);
                TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32);
                TestDelegate writeArray            = () => fileSystem.File.WriteAllLines(path, fileContentArray);
                TestDelegate writeArrayUtf32       = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32);

                // IEnumerable
                yield return(new TestCaseData(writeEnumberable)
                             .SetName("WriteAllLines(string, IEnumerable<string>) input: " + path));

                yield return(new TestCaseData(writeEnumberableUtf32)
                             .SetName("WriteAllLines(string, IEnumerable<string>, Encoding.UTF32) input: " + path));

                // string[]
                yield return(new TestCaseData(writeArray)
                             .SetName("WriteAllLines(string, string[]) input: " + path));

                yield return(new TestCaseData(writeArrayUtf32)
                             .SetName("WriteAllLines(string, string[], Encoding.UTF32) input: " + path));
            }
Beispiel #60
0
 public void Multiple(TestDelegate testDelegate)
 {
     Assert.Multiple(testDelegate);
 }