public async Async.Task OneNoteTryCreateNotebookWithInvalidChars()
        {
            try
            {
                var newNotebook = new Notebook()
                {
                    DisplayName = $"Notebook created from test, ?*\\/:<>|'"
                };

                Notebook notebook = await graphClient.Me.Onenote.Notebooks.Request().AddAsync(newNotebook);
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                StringAssert.Contains(e.Error.Message, "The notebook name value contains invalid characters");
            }

            catch (Exception e)
            {
                Assert.Fail("Error code: {0}", e.Message);
            }
        }
示例#2
0
        public void SubscribeTest()
        {
            string actual = null;

            _wss.Setup(w => w.Send(It.IsAny <string>())).Callback <string>(c => actual = c);

            var gotBTCUSD = false;
            var gotGBPUSD = false;
            var gotBTCETH = false;

            _unit.Subscribe(GetSubscriptionDataConfig <Tick>(Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), Resolution.Tick), (s, e) => { gotBTCUSD = true; });
            StringAssert.Contains("[\"BTC-USD\"]", actual);
            _unit.Subscribe(GetSubscriptionDataConfig <Tick>(Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM), Resolution.Tick), (s, e) => { gotGBPUSD = true; });
            _unit.Subscribe(GetSubscriptionDataConfig <Tick>(Symbol.Create("BTCETH", SecurityType.Crypto, Market.GDAX), Resolution.Tick), (s, e) => { gotBTCETH = true; });
            StringAssert.Contains("[\"BTC-USD\",\"BTC-ETH\"]", actual);
            Thread.Sleep(1000);

            Assert.IsFalse(gotBTCUSD);
            Assert.IsTrue(gotGBPUSD);
            Assert.IsFalse(gotBTCETH);
        }
示例#3
0
        public void Debit_WhenAmountIsMoreThanBalance_ShouldThrowArgumentOutOfRange()
        {
            // Arrange
            double      beginningBalance = 11.99;
            double      debitAmount      = 20.0;
            BankAccount account          = new BankAccount("Mr. Bryan Walton", beginningBalance);

            // Act
            try
            {
                account.Debit(debitAmount);
            }
            catch (System.ArgumentOutOfRangeException e)
            {
                // Assert
                StringAssert.Contains(e.Message, BankAccount.DebitAmountExceedsBalanceMessage);
                return;
            }

            Assert.Fail("The expected exception was not thrown.");
        }
示例#4
0
        public void RepeatingGroup_ReuseObject()
        {
            QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary();
            dd.LoadFIXSpec("FIX42");

            QuickFix.FIX42.News news = new QuickFix.FIX42.News(new QuickFix.Fields.Headline("Foo headline"));

            QuickFix.FIX42.News.LinesOfTextGroup group = new QuickFix.FIX42.News.LinesOfTextGroup();
            group.Text = new QuickFix.Fields.Text("line1");
            news.AddGroup(group);
            group.Text = new QuickFix.Fields.Text("line2");
            news.AddGroup(group);

            string raw = news.ToString();

            string nul = "\x01";

            StringAssert.Contains(
                nul + "33=2" + nul + "58=line1" + nul + "58=line2",
                raw);
        }
        public void TestKeywords_OverrideWithHigherPriority_Respected(ConnectionStringKeywordPriority newPriority)
        {
            var acc = new ConnectionStringKeywordAccumulator(DatabaseType.MicrosoftSQLServer);

            acc.AddOrUpdateKeyword("Pooling", "false", ConnectionStringKeywordPriority.SystemDefaultHigh);

            DbConnectionStringBuilder connectionStringBuilder = helpers[DatabaseType.MicrosoftSQLServer].GetConnectionStringBuilder("localhost", "mydb", "frank", "kangaro");

            StringAssert.DoesNotContain("pooling", connectionStringBuilder.ConnectionString);

            acc.EnforceOptions(connectionStringBuilder);

            StringAssert.Contains("Pooling=False", connectionStringBuilder.ConnectionString);

            //attempt override with low priority setting it to true (note we flipped case of P just to be a curve ball)
            acc.AddOrUpdateKeyword("pooling", "true", newPriority);

            acc.EnforceOptions(connectionStringBuilder);

            StringAssert.Contains("Pooling=True", connectionStringBuilder.ConnectionString);
        }
示例#6
0
        public void PropagatesUnIgnoredExceptions()
        {
            var ex        = new NoSuchWindowException("");
            var condition = GetCondition <object>(() => { NonInlineableThrow(ex); return(null); });

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout         = TimeSpan.FromMilliseconds(0);
            wait.PollingInterval = TimeSpan.FromSeconds(2);
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(NoSuchFrameException));

            var caughtException = Assert.Throws <NoSuchWindowException>(() => wait.Until(condition));

            Assert.AreSame(ex, caughtException);

            // Regression test for issue #6343
            StringAssert.Contains("NonInlineableThrow", caughtException.StackTrace, "the stack trace must include the call to NonInlineableThrow()");
        }
示例#7
0
            public void GivenSereverNameInConfigIsNull_WhenCreatesAnPluginInstance_ThenThrowException()
            {
                var message = string.Empty;

                try
                {
                    // Arrange
                    var configManager = new Mock <IConfigManager>();
                    configManager.Setup(x => x.ServerName).Returns(string.Empty);

                    // Act
                    IPlugin plugin = new SqlServerPlugin(configManager.Object);
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }

                // Assert
                StringAssert.Contains(message, "SqlServerPlugin : configManager.ServerName is null or empty.");
            }
        public void Should_fail_for_snapshot()
        {
            var ex = Assert.ThrowsAsync <ArgumentException>(async() =>
            {
                await Scenario.Define <Context>()
                .WithEndpoint <ScopeEndpoint>(g =>
                {
                    g.CustomConfig(c =>
                    {
                        var transportSettings = (MsmqTransport)c.ConfigureTransport();
                        transportSettings.TransportTransactionMode = TransportTransactionMode.TransactionScope;
                        transportSettings.ConfigureTransactionScope(isolationLevel: IsolationLevel.Snapshot);
                    });
                    g.When(b => b.SendLocal(new MyMessage()));
                })
                .Done(c => c.Done)
                .Run();
            });

            StringAssert.Contains("Isolation level `Snapshot` is not supported by the transport. Consider not sharing the transaction between transport and persistence if persistence should use `IsolationLevel.Snapshot` by using `TransportTransactionMode.SendsAtomicWithReceive` or lower.", ex.Message);
        }
示例#9
0
        public void ShouldThrowArgumentNullExceptionWithCorrectMessage_WhenNullOrEmptyCartIdIsPassed(string cartId)
        {
            // Arrange
            var expectedExMessage = "Cart id cannot be null.";

            var mockedUnitOfWork             = new Mock <IUnitOfWork>();
            var mockedCartProductFactory     = new Mock <ICartProductFactory>();
            var mockedCartProductRepository  = new Mock <IGenericRepository <CartProduct> >();
            var mockedShoppingCartRepository = new Mock <IGenericRepository <ShoppingCart> >();

            var shoppingCartsService = new ShoppingCartsService(mockedUnitOfWork.Object,
                                                                mockedCartProductFactory.Object,
                                                                mockedShoppingCartRepository.Object,
                                                                mockedCartProductRepository.Object);

            // Act and Assert
            var exception = Assert.Throws <ArgumentNullException>(() =>
                                                                  shoppingCartsService.GetCart(cartId));

            StringAssert.Contains(expectedExMessage, exception.Message);
        }
示例#10
0
        public void ShouldLogModuleInitializationError()
        {
            IContainerFacade containerFacade = new MockContainerAdapter();
            var logger  = new MockLogger();
            var service = new ModuleLoader(containerFacade, logger);

            ExceptionThrowingModule.wasInitializedOnce = false;
            //var exceptionModule = new ModuleInfo(typeof(ExceptionThrowingModule).Assembly.Location, typeof(ExceptionThrowingModule).FullName, "ExceptionThrowingModule");

            var exceptionModule = new ModuleInfo(typeof(ExceptionThrowingModule).Assembly.FullName, typeof(ExceptionThrowingModule).FullName, "ExceptionThrowingModule");

            try
            {
                service.Initialize(new[] { exceptionModule });
            }
            catch (ModuleLoadException)
            {
            }
            Assert.IsNotNull(logger.LastMessage);
            StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
        }
        public void ReturnsErrorMessage_WhenInvalidAmountPassed()
        {
            // Arrange
            var cardServiceMock  = new Mock <ICardService>();
            var dateTimeProvMock = new Mock <IDateTimeProvider>();
            var controller       = SetupController(cardServiceMock, dateTimeProvMock);

            var expiryDate  = new DateTime(2017, 5, 10);
            var dateTimeNow = new DateTime(2018, 12, 12);

            dateTimeProvMock
            .Setup(d => d.Now)
            .Returns(dateTimeNow);

            // Act
            var    result    = controller.IsValidExpiryDate(expiryDate);
            string resultMsg = result.Value.ToString();

            // Assert
            StringAssert.Contains(resultMsg, "Invalid expiry date");
        }
        public void ReturnNotValidEmployeeId_WhenSecondParameterCannotBeParsedToInt(params string[] parameters)
        {
            //Arrange
            var dbMock = new Mock <IDatabase>();

            var storeMock           = new Mock <Store>();
            var storeRepositoryMock = new Mock <IStoreRepository>();

            storeRepositoryMock.Setup(s => s.SingleOrDefault(It.IsAny <Expression <Func <Store, bool> > >())).Returns(storeMock.Object);

            dbMock.Setup(d => d.Stores).Returns(storeRepositoryMock.Object);

            var sut            = new RemoveStoreEmployeeCommand(dbMock.Object);
            var expectedString = "Not Valid Employee Id";

            //Act
            var result = sut.Execute(parameters);

            //Assert
            StringAssert.Contains(expectedString, result);
        }
示例#13
0
文件: OwinTests.cs 项目: aws/cta
        public void TestSignalR(string version)
        {
            TestSolutionAnalysis results = AnalyzeSolution("SignalR.sln", tempDir, downloadLocation, version);

            string projectDir = results.ProjectResults.FirstOrDefault().ProjectDirectory;
            var csProjContent = results.ProjectResults.FirstOrDefault().CsProjectContent;
            var startupText = File.ReadAllText(Path.Combine(projectDir, "Startup.cs"));
            var programText = File.ReadAllText(Path.Combine(projectDir, "Program.cs"));

            StringAssert.AreEqualIgnoringCase(ExpectedOutputConstants.SignalRProgram.NormalizeNewLineChars(), programText.NormalizeNewLineChars());
            StringAssert.AreEqualIgnoringCase(ExpectedOutputConstants.SignalRStartup.NormalizeNewLineChars(), startupText.NormalizeNewLineChars());

            //Check that package has been added:
            StringAssert.Contains(@"Microsoft.AspNetCore.Diagnostics", csProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.Server.Kestrel", csProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.Hosting", csProjContent);
            StringAssert.Contains(@"Microsoft.AspNetCore.SignalR", csProjContent);

            //Check that correct version is used
            Assert.True(csProjContent.IndexOf(string.Concat(">", version, "<")) > 0);
        }
示例#14
0
        public async Async.Task OneNoteCreatePageWithHtmlStream()
        {
            string testString = ". Choose positive.";

            // Create the request body.
            string htmlBody = $"<!DOCTYPE html><html><head><title>OneNoteAddPageHtmlWithStream test created this{testString}</title></head>" +
                              "<body>Generated from the test with the partial</body></html> ";

            byte[] byteArray = Encoding.ASCII.GetBytes(htmlBody);

            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                // Create a OneNote page.
                testPage = await graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().AddAsync(stream, "text/html");
            }

            Assert.IsNotNull(testPage, "EXPECTED: A OneNote page, ACTUAL: null");
            StringAssert.Contains(testPage.Title, testString, "EXPECTED: Test string from the create action in the title.");

            TestPageCleanUp();
        }
示例#15
0
        public void With_JoinWithBothPrimaryKeysOnBothSides()
        {
            //=========-----------action
            var query = from p in PersonEntityService.GetQuery().With("NOLOCK")
                        join t in PersonEntityService.DataContext.GetTable <Sequences.TableEntity>().With("NOLOCK") on p.Id equals t.Id
                        select p;


            //=========-----------assertion

            //проверяем что sql содержит хинты
            var sqlText = ((IExpressionQuery <Sequences.PersonEntity>)query).SqlText;

            StringAssert.Contains("[CoreTest].[dbo].[Person] [p] WITH (NOLOCK)", sqlText);
            StringAssert.Contains("[CoreTest].[dbo].[Table] [t] WITH (NOLOCK)", sqlText);

            //проверяем что sql отрабатывает без эксепшна
            Assert.DoesNotThrow(() => {
                var res = query.ToList();
            });
        }
示例#16
0
        public void Test_AggregateEditorUI_NoExtractableColumns()
        {
            //Create a Catalogue with an AggregateConfiguration that doesn't have any extractable columns yet
            var cata   = WhenIHaveA <Catalogue>();
            var config = new AggregateConfiguration(Repository, cata, "My config");

            //these commands should be impossible
            var cmd = new ExecuteCommandAddNewAggregateGraph(ItemActivator, cata);

            Assert.IsTrue(cmd.IsImpossible);
            StringAssert.Contains("no extractable columns", cmd.ReasonCommandImpossible);

            //and if the broken config is activated
            var ui = AndLaunch <AggregateEditorUI>(config);

            //it should not launch and instead show the following message
            var killed = ItemActivator.Results.KilledForms.Single();

            Assert.AreEqual(ui.ParentForm, killed.Key);
            StringAssert.Contains("no extractable columns", killed.Value.Message);
        }
示例#17
0
        public async Task Test_StreamHelper_KnownFolder()
        {
            var folder = KnownFolderId.PicturesLibrary;

            Assert.IsFalse(await StreamHelper.IsKnownFolderFileExistsAsync(folder, FILENAME));

            var storageFile = await StorageFileHelper.WriteTextToKnownFolderFileAsync(folder, SAMPLETEXT, FILENAME);

            Assert.IsNotNull(storageFile);

            Assert.IsTrue(await StreamHelper.IsKnownFolderFileExistsAsync(folder, FILENAME));

            using (var stream = await StreamHelper.GetKnowFoldersFileStreamAsync(folder, FILENAME))
            {
                var loadedText = await stream.ReadTextAsync(Encoding.UTF8);

                StringAssert.Contains(loadedText, SAMPLETEXT);
            }

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
示例#18
0
        public void TestPrintValuesWhereDotE()
        {
            using (StringWriter sw = new StringWriter())
            {
                Dictionary <string, string> dict = new Dictionary <string, string>();
                dict.Add("f.e", "for example");
                dict.Add("etc.", "and so on");
                dict.Add("i.e", "more precisely");
                dict.Add("jne", "ja niin edelleen");

                TextWriter stdout = Console.Out;
                Console.SetOut(sw);
                Program.PrintValuesOfKeysWhere(dict, ".e");
                Console.SetOut(stdout);

                // Assert
                StringAssert.Contains("for example", sw.ToString().Replace("\r\n", "\n"), "You should print the values!");
                StringAssert.Contains("more precisely", sw.ToString().Replace("\r\n", "\n"), "You should print the values!");
                StringAssert.DoesNotContain("ja niin edelleen", sw.ToString().Replace("\r\n", "\n"), "You should print the values!");
            }
        }
示例#19
0
        public async Task Form_bad_data_throws()
        {
            const string input = @"1 1
0 0 W
X";

            var parameters = new Dictionary <string, string>
            {
                ["world"] = input
            };

            using (var content = new FormUrlEncodedContent(parameters))
            {
                using (var response = await client.PostAsync("/", content))
                {
                    var value = await response.Content.ReadAsStringAsync();

                    StringAssert.Contains(value, "<span class=\"error\">");
                }
            }
        }
        public void CommentEditPresenter_GetCommentShouldReturnMessageWhenNotVisible()
        {
            var view = new Mock <ICommentEditView>();

            view.SetupAllProperties();
            var forumData = new Mock <IForumData>();

            var presenter = new CommentEditPresenter(view.Object, forumData.Object);

            var comment = new Comment()
            {
                Id = 1, IsVisible = false
            };


            forumData.Setup(t => t.CommentsRepository.GetCommentById(It.Is <int>(x => x == 1))).Returns(comment);

            view.Raise(v => v.GetComment += null, view.Object, new GetByIdEventArgs(1));

            StringAssert.Contains("File not found", view.Object.Model.Error);
        }
        public void ReturnAStringContainingTheseMarks_WhenStudentHasMarksInMarksList()
        {
            // arrange
            string firstName = "validName";
            string lastName  = "validName";
            Grade  grade     = Grade.Seventh;

            var student = new Student(firstName, lastName, grade);

            var mark = new Mock <Contracts.IMark>();

            student.Marks.Add(mark.Object);

            string expected = "these marks";

            // act
            string marksString = student.ListMarks();

            // assert
            StringAssert.Contains(expected, marksString);
        }
示例#22
0
        public void EncapsulatePrivateField_EnumMemberConflict()
        {
            //5.2.3.4: An enum member name may not be the same as any variable name, or constant name that is defined within the same module
            const string inputCode =
                @"

Public Enum NumberTypes 
     Whole = -1 
     Integral = 0 
     Rational_1 = 1 
End Enum

Private rati|onal As NumberTypes
";

            var presenterAction = Support.UserAcceptsDefaults();
            var actualCode      = Support.RefactoredCode(inputCode.ToCodeString(), presenterAction);

            StringAssert.Contains("Public Property Get Rational() As NumberTypes", actualCode);
            StringAssert.Contains("Rational = rational_2", actualCode);
        }
示例#23
0
        public void Find_All_Users_Of_PublicBaseClass()
        {
            CommandParser parser = new CommandParser();
            CommandData   data   = parser.Parse(new string[]
            {
                "-whousestype", "PublicBaseClass", TestConstants.BaseLibV1,
                "-in", TestConstants.DependantLibV1
            });
            WhoUsesTypeCommand cmd = (WhoUsesTypeCommand)data.GetCommand();

            cmd.Out = new StringWriter();
            cmd.Execute();
            string output = cmd.Out.ToString();

            string[] lines = output.Split(new char[] { '\n' });
            Assert.IsTrue(lines.Length > 23);
            StringAssert.Contains("m_Base", output);
            StringAssert.Contains("private void ReadFromField()", output);
            StringAssert.Contains("private void WriteToField()", output);
            StringAssert.Contains("private void CallFunctionFromBaseClass()", output);
        }
示例#24
0
        public void PropertyNameNotDuplicated()
        {
            const string inputCode =
                @"Public var|iable As Integer, variable1 As Long, variable2 As Integer";

            var userInput = new UserInputDataObject()
                            .UserSelectsField("variable")
                            .UserSelectsField("variable1")
                            .UserSelectsField("variable2");

            var presenterAction = Support.SetParameters(userInput);
            var actualCode      = Support.RefactoredCode(inputCode.ToCodeString(), presenterAction);

            StringAssert.Contains("Public Property Get Variable() As Integer", actualCode);
            StringAssert.Contains("Variable = variable_1", actualCode);
            StringAssert.Contains("Public Property Get Variable1() As Long", actualCode);
            StringAssert.Contains("Variable1 = variable1_1", actualCode);
            StringAssert.Contains("Public Property Get Variable2() As Integer", actualCode);
            StringAssert.Contains("Variable2 = variable2_1", actualCode);
            StringAssert.DoesNotContain("Public Property Get Variable3() As Integer", actualCode);
        }
示例#25
0
        public async Task UpdatePoolConstantFromFakeHandlerReturnTheGoodUuid()
        {
            FakeHTTP.ReturnMessage = HttpPoolObject.PoolsListBodiesWithPaging;
            ConfigType type    = ConfigType.Pool;
            CommandApi command = CommandApi.UpdateConstant;

            var commandLauncher = new CommandGeneric <QPool, CommandValues.GenericInfoCommandValue>(
                new QPoolsRetriever(),
                new UpdatePoolConstantCommand(),
                FormatTable,
                FakeApi
                );

            string returnString = await commandLauncher.RunAndPrintCommandAsync(
                new ConstantUpdateConfiguration(type, command) { ConstantName = "SOME_CONSTANT", ConstantValue = "some-new-value" },
                FalsePrinter);

            string expected1 = "796a5321-0001-4a5c-2f42-54cce169dff8";

            StringAssert.Contains(expected1, returnString);
        }
        public void Test_BuildPropDef_WithNoPropName_ShouldRaiseError()
        {
            //---------------Set up test pack-------------------
            const string propertyName = "";

            //---------------Assert Precondition----------------
            Assert.IsEmpty(propertyName);
            //---------------Execute Test ----------------------
            try
            {
                GetPropDefBuilder <Car>()
                .WithPropertyName(propertyName)
                .Build();
                Assert.Fail("Expected to throw an HabaneroArgumentException");
            }
            //---------------Test Result -----------------------
            catch (HabaneroArgumentException ex)
            {
                StringAssert.Contains("The argument 'propertyName' is not valid. Argument cannot be a zero length string", ex.Message);
            }
        }
        public void TestExceptionCase()
        {
            Robot Robo = new Robot();

            int[] RoboSouthArray;
            int[] RoboNorthArray;
            int[] RoboEastArray;
            int[] RoboWestArray;
            try
            {
                RoboNorthArray = Robo.MoveNorth(2);
                RoboSouthArray = Robo.MoveSouth(1, RoboNorthArray.Last().ToString());
                RoboEastArray  = Robo.MoveEast(3, RoboSouthArray.Last());
                RoboWestArray  = Robo.MoveWest(4, RoboEastArray.Last(), RoboSouthArray.Last());
            }
            catch (ArgumentNullException e)
            {
                StringAssert.Contains(e.Message, "enter numeric number < 10");
            }
            Assert.Fail("No exception was thrown");
        }
        public async Task CreateRsaHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateRsaKeyOptions options   = new CreateRsaKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey         rsaHsmkey = await Client.CreateRsaKeyAsync(options);

            RegisterForCleanup(keyName);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyName);

            AssertKeyVaultKeysEqual(rsaHsmkey, keyReturned);

            using MemoryStream ms = new();
            await JsonSerializer.SerializeAsync(ms, keyReturned.Key);

            string json = Encoding.UTF8.GetString(ms.ToArray());

            StringAssert.Contains($@"""kid"":""{keyReturned.Id}""", json);
            StringAssert.Contains(@"""kty"":""RSA-HSM""", json);
        }
示例#29
0
        public void AppServer_SaveResource_WhenSavingWorkerService_ExpectSaved()
        {
            //------------Setup for test--------------------------
            CommunicationController coms = new CommunicationController {
                ServiceName = "SaveResourceService"
            };

            var id  = Guid.NewGuid().ToString();
            var tmp = new StringBuilder(CreateService(id, "[[Id]]"));

            coms.AddPayloadArgument("ResourceXml", tmp);
            coms.AddPayloadArgument("WorkspaceID", Guid.Empty.ToString());

            string expected = string.Format("Added DbService '{0}'", id);

            //------------Execute Test---------------------------
            var result = coms.ExecuteCommand <ExecuteMessage>(_connection, Guid.Empty);

            //------------Assert Results-------------------------
            StringAssert.Contains(result.Message.ToString(), expected, "Got [ " + result.Message + " ]");
        }
示例#30
0
        public void Open()
        {
            ServiceHost host = new ServiceHost(typeof(ZeroOperationsImpl));

            host.AddServiceEndpoint(typeof(IHaveZeroOperarationsContract), new BasicHttpBinding(), "http://localhost/echo");

            try {
                host.Open();
                Assert.Fail("InvalidOperationException expected");
            }
            catch (InvalidOperationException e) {
                //"ContractDescription 'IHaveZeroOperarationsContract' has zero operations; a contract must have at least one operation."
                StringAssert.Contains("IHaveZeroOperarationsContract", e.Message);
            }
            finally {
                if (host.State == CommunicationState.Opened)
                {
                    host.Close();                      // It is to make sure to close unexpectedly opened host if the test fail.
                }
            }
        }