コード例 #1
0
        public void ValidaCuraFeitaPeloProprioPersonagemComErro()
        {
            string otherName = "OtherPerson";

            var _otherCharacter = new Character()
            {
                Name = otherName
            };

            var _newHealth = 1000;

            _character.UpHealth(_newHealth);

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.BeCure(_otherCharacter);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "A character can only heal characters of his own faction.");

                _character.DownHealth(_newHealth);

                Assert.AreEqual(_character.Health, _originalHealt);
                Assert.AreEqual(_character.Level, _originalLevel);
                Assert.AreEqual(_character.Alive, true);
                Assert.AreNotEqual(_character.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #2
0
        public void Throws_WithActionThatThrowsAndDifferentTypeExpectedException()
        {
            AssertFailedException exception = Assert.ThrowsException <AssertFailedException>(() => AssertEx.Throws(() => { throw new ArgumentException("fake-message"); }, new PreConditionException("blah")));

            Assert.IsNotNull(exception);
            Assert.AreEqual("Assert.AreEqual failed. Expected:<Pkgdef_CSharp.PreConditionException>. Actual:<System.ArgumentException>. Wrong exception type thrown.", exception.Message);
        }
コード例 #3
0
        public void Throws_WithActionThatThrowsAndDifferentMessageExpectedException()
        {
            AssertFailedException exception = Assert.ThrowsException <AssertFailedException>(() => AssertEx.Throws(() => { throw new ArgumentException("fake-message"); }, new ArgumentException("blah")));

            Assert.IsNotNull(exception);
            Assert.AreEqual("Assert.AreEqual failed. Expected:<blah>. Actual:<fake-message>. Wrong exception message.", exception.Message);
        }
コード例 #4
0
        public void ValidaAtaqueFeitoPersonagemPorOutroPersonagemRangedForaAlcance()
        {
            string otherName       = "OtherPerson";
            var    _potenciaAtaque = 10;

            var _otherCharacter = new Character(TypeOfFighter.Ranged)
            {
                Name = otherName, Position = 30
            };
            var _newHealth = 5000;

            _character.UpHealth(_newHealth);

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.MakeAttack(_potenciaAtaque, _otherCharacter);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "Opponent out of reach.");
                Assert.AreEqual(_otherCharacter.Health, _originalHealt);
                Assert.AreEqual(_otherCharacter.Level, _originalLevel);
                Assert.AreEqual(_otherCharacter.Alive, true);
                Assert.AreNotEqual(_otherCharacter.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #5
0
        public void Fail_PropagatesErrorMessage()
        {
            AssertFailedException exception = Assert.ThrowsException <AssertFailedException>(
                () => NullableAssert.Fail(s_message, s_parameters));

            StringAssert.Contains(exception.Message, s_expectedMessage);
        }
コード例 #6
0
        public void TestIfUpdateTaskFowViewThrowNullReferenceException()
        {
            Task actualTask            = _persistance.UpdateTaskFowView(null, "", "", "", "", 0);
            NullReferenceException obj = new NullReferenceException();

            AssertFailedException.ReferenceEquals(obj, actualTask);
        }
コード例 #7
0
ファイル: FileIOTest.cs プロジェクト: amidsaif/WeatherApp
        public void TestGetFileContents()
        {
            string          fileName        = @"C\Cities.txt";
            BussionessLogic bussionessLogic = new BussionessLogic();
            OpenWeatherMap  openWeatherMap  = bussionessLogic.GetFileContents(fileName);

            AssertFailedException.Equals(null, openWeatherMap);
        }
コード例 #8
0
        private static void logFail(AssertFailedException ex, string expressionAsserted, string description)
        {
            if (failedAssertions.Length == 0)
            {
                failedAssertions.AppendLine("TOTAL FAILED ASSERTIONS");
                failedAssertions.AppendLine("---------------------------------------------------------------------------------------");
            }

            failedAssertions.AppendLine(string.Format("{0} {1}", ex.Message, description + ": FAILED"));
        }
コード例 #9
0
        /// <summary>
        /// Asserts that the code under test given by the <paramref name="codeThatThrows"/> parameter
        /// throws an exception of a given type with a ParamName value given by the <paramref name="paramName"/> parameter.
        /// </summary>
        /// <param name="exceptionType">The <see cref="Type"/> of exception that the code under test should throw.</param>
        /// <param name="noExceptionMessage">
        /// The message to include with the failed <see cref="Assert"/> if the code under test does not
        /// throw an exception.
        /// </param>
        /// <param name="paramName">The name of the null parameter that results in the <see cref="ArgumentNullException"/>.</param>
        /// <param name="codeThatThrows">The code under test that is expected to throw an <see cref="ArgumentNullException"/>.</param>
        public static void Throws(Type exceptionType, string noExceptionMessage, Action codeThatThrows, string paramName)
        {
            Exception             actualException       = null;
            AssertFailedException assertFailedException = null;

            try
            {
                codeThatThrows();
            }
            catch (Exception exception)
            {
                actualException = exception;

                // Let assert failure in the callback escape these checks
                assertFailedException = exception as AssertFailedException;
                if (assertFailedException != null)
                {
                    throw;
                }
            }
            finally
            {
                if (assertFailedException == null)
                {
                    if (actualException == null)
                    {
                        Assert.Fail(noExceptionMessage);
                    }

                    Assert.IsInstanceOfType(
                        actualException,
                        exceptionType,
                        string.Format(
                            "Expected an exception of type '{0}' but encountered an exception of type '{1}' with the message: {2}.",
                            exceptionType.FullName,
                            actualException.GetType().FullName,
                            actualException.Message));

                    if (paramName != null)
                    {
                        PropertyInfo propInfo        = actualException.GetType().GetProperty("ParamName");
                        string       actualParamName = propInfo == null
                                                    ? "<not available>"
                                                    : propInfo.GetValue(actualException, null) as string;
                        Assert.AreEqual(
                            paramName,
                            actualParamName,
                            string.Format(
                                "Expected exception to have paramName='{0}' but found instead '{1}'",
                                paramName,
                                actualParamName));
                    }
                }
            }
        }
コード例 #10
0
 public void TesteValor_MenorQueZero()
 {
     try
     {
         string valorExtenso = ValorMonetario.Converte(-5);
     }
     catch (Exception ex)
     {
         AssertFailedException.Equals(MensagemValorInvalido, ex);
     }
 }
コード例 #11
0
 public void TesteValor_NaoNumero()
 {
     try
     {
         string valorExtenso = ValorMonetario.Converte("asdfasdfsa");
     }
     catch (Exception ex)
     {
         AssertFailedException.Equals(MensagemValorInvalido, ex);
     }
 }
コード例 #12
0
 public void TesteValor_MaiorQueTresAlgarismos()
 {
     try
     {
         string valorExtenso = ValorMonetario.Converte(5000);
     }
     catch (Exception ex)
     {
         AssertFailedException.Equals(MensagemValorInvalido, ex);
     }
 }
コード例 #13
0
 public Task RunTransferJob(TransferJobBase job, Action <double, double> progressReport, CancellationToken cancellationToken)
 {
     try
     {
         return(runnerValidation(job));
     }
     catch (AssertFailedException e)
     {
         this.assertException = e;
         throw new MockupException("AssertFailed");
     }
 }
コード例 #14
0
ファイル: UnitTest1.cs プロジェクト: Forestf90/TimeWorkRecord
        public void Update()
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-0PBRBDG;Initial Catalog=Dolars;Integrated Security=True");

            //con.Open();

            con.Open();
            string     a   = @"Update Pracownik Set DataZwolnienia = null";
            SqlCommand cmd = new SqlCommand(a, con);

            // cmd.ExecuteNonQuery();
            AssertFailedException.Equals(true, cmd.ExecuteNonQuery());
        }
コード例 #15
0
ファイル: UnitTest1.cs プロジェクト: Forestf90/TimeWorkRecord
        public void Delete()
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-0PBRBDG;Initial Catalog=Dolars;Integrated Security=True");

            //con.Open();

            con.Open();
            string     a   = @"Delete from Pracownik where Nazwisko='Stachnik'";
            SqlCommand cmd = new SqlCommand(a, con);

            // cmd.ExecuteNonQuery();
            AssertFailedException.Equals(true, cmd.ExecuteNonQuery());
        }
コード例 #16
0
ファイル: ExceptionAssert.cs プロジェクト: nuxleus/WCFWeb
        /// <summary>
        /// Asserts that an exception of type <typeparamref name="TException"/> is thrown
        /// and calls the caller back to do more fine-grained checking.
        /// </summary>
        /// <typeparam name="TException">The type of exception that must be thrown.</typeparam>
        /// <param name="noExceptionMessage">The message to assert if no exception is thrown.</param>
        /// <param name="codeThatThrows">Code that is expected to trigger the exception. Should not be <c>null</c>.</param>
        /// <param name="codeThatChecks">Code called after the exception is caught to do finer-grained checking. Should not be <c>null</c>.</param>
        public static void Throws <TException>(
            string noExceptionMessage,
            Action codeThatThrows,
            Action <TException> codeThatChecks) where TException : Exception
        {
            Assert.IsNotNull(codeThatThrows, "The 'codeThatThrows' parameter should not be null.");
            Assert.IsNotNull(codeThatChecks, "The 'codeThatChecks' parameter should not be null.");

            Exception             actualException       = null;
            AssertFailedException assertFailedException = null;

            try
            {
                codeThatThrows();
            }
            catch (Exception exception)
            {
                actualException = exception;

                // Let assert failure in the callback escape these checks
                assertFailedException = exception as AssertFailedException;
                if (assertFailedException != null)
                {
                    throw;
                }
            }
            finally
            {
                if (assertFailedException == null)
                {
                    if (actualException == null)
                    {
                        string message = string.IsNullOrWhiteSpace(noExceptionMessage) ?
                                         string.Format("Expected an exception of type '{0}' but no exception was thrown.", typeof(TException).FullName) :
                                         noExceptionMessage;
                        Assert.Fail(message);
                    }

                    Assert.IsInstanceOfType(
                        actualException,
                        typeof(TException),
                        string.Format(
                            "Expected an exception of type '{0}' but encountered an exception of type '{1}' with the message: {2}.",
                            typeof(TException).FullName,
                            actualException.GetType().FullName,
                            actualException.Message));

                    codeThatChecks((TException)actualException);
                }
            }
        }
コード例 #17
0
ファイル: UnitTest1.cs プロジェクト: Forestf90/TimeWorkRecord
        public void Insert()
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-0PBRBDG;Initial Catalog=Dolars;Integrated Security=True");

            //con.Open();

            con.Open();
            string     a   = @"INSERT INTO Pracownik Values('11' ,'Paulina' , 'Stachnik', '2000.01.01' ,
                            null , '50' , 'o prace' , '8')";
            SqlCommand cmd = new SqlCommand(a, con);

            // cmd.ExecuteNonQuery();
            AssertFailedException.Equals(true, cmd.ExecuteNonQuery());
        }
コード例 #18
0
        public void Save(AssertFailedException afe)
        {
            string methodName = Get_Executing_Method_Name(afe);
            string getDate    = Get_Date_Now();
            string content    = getDate + Environment.NewLine +
                                "Where: " + methodName + Environment.NewLine +
                                "What: " + afe.Message + Environment.NewLine + Environment.NewLine;
            //File.WriteAllText("failed_tests.txt", content);

            TextWriter tw = new StreamWriter("failed_tests.txt", true);

            tw.Write(content);
            tw.Close();
        }
コード例 #19
0
        private static void ExecuteCodeUnderTest(Type type, object obj, string messageOnFail, Action <Type, object> codeUnderTest)
        {
            Exception             actualException       = null;
            AssertFailedException assertFailedException = null;

            try
            {
                codeUnderTest(type, obj);
            }
            catch (Exception exception)
            {
                actualException = exception;

                // Let assert failure in the callback escape these checks
                assertFailedException = exception as AssertFailedException;
                if (assertFailedException != null)
                {
                    throw;
                }
            }
            finally
            {
                if (assertFailedException == null && actualException != null)
                {
                    string failureMessage = null;
                    if (type.IsValueType)
                    {
                        failureMessage = string.Format("Executing with an instance of type '{0}' and value '{1}' failed.", type.FullName, obj.ToString());
                    }
                    else
                    {
                        failureMessage = string.Format("Executing with an instance of type '{0}' failed.", type.FullName);
                    }

                    failureMessage = string.Format("{0}: {1}.", failureMessage, actualException.Message);

                    if (!string.IsNullOrWhiteSpace(messageOnFail))
                    {
                        failureMessage = string.Format(" {0}", failureMessage);
                    }

                    throw new AssertFailedException(failureMessage, actualException);
                }
            }
        }
コード例 #20
0
        private AssertFailedException GetDifference(string expected, string actual, AssertFailedException originalException)
        {
            var expectedParts = UrlUtilities.CrackUrl(expected);
            var actualParts   = UrlUtilities.CrackUrl(actual);

            foreach (var part in actualParts.AllKeys)
            {
                var expectedVal = expectedParts[part];
                var actualVal   = actualParts[part];

                if (expectedVal != actualVal)
                {
                    Assert.Fail($"{part} was different. Expected: {expectedVal}. Actual: {actualVal}.{Environment.NewLine}{Environment.NewLine}{originalException.Message}");
                }
            }

            return(originalException);
        }
コード例 #21
0
        private AssertFailedException GetDifference(string expected, string actual, AssertFailedException originalException)
        {
            var expectedParts = PrtgAPI.Helpers.UrlHelpers.CrackUrl(expected);
            var actualParts   = PrtgAPI.Helpers.UrlHelpers.CrackUrl(actual);

            foreach (var part in actualParts.AllKeys)
            {
                var expectedVal = expectedParts[part];
                var actualVal   = actualParts[part];

                if (expectedVal != actualVal)
                {
                    Assert.Fail($"{part} was different. Expected: {expectedVal}. Actual: {actualVal}.\r\n\r\n{originalException.Message}");
                }
            }

            return(originalException);
        }
コード例 #22
0
        [TestMethod]//Test to check if DoConnection throws an exception if accountnumber is not passed
        public void HomepageController_DoConnectionMethod_ThrowsExceptionTest()
        {
            //Arrange
            string resultstr = tpaController.Post(input);
            string key       = resultstr.Substring(38);

            key     = key.Replace(Constants.APPLICATION_URL_DUMMY_TEXT, "/");
            accInfo = AvaTaxProfileAssistantHelper.GetAccountInfoBySecureKey(key);
            accInfo.AccountNumber = "";
            Exception e = new Exception();

            //Act

            homeController.DoConnection(ref IsConnected, ref IsChoseCompany, ref WhereToCollectTax, ref NexusWarning, null);

            //Assert

            AssertFailedException.Equals("Object reference not set to an instance of an object.", e);
        }
コード例 #23
0
        public void RetryAssert(Action action, int timeoutMilliseconds, int retryIntervalMilliseconds = 50)
        {
            AssertFailedException ex = new AssertFailedException("Timeout exceeded before positive check");
            var timeout = DateTime.Now.AddMilliseconds(timeoutMilliseconds);

            while (timeout.Subtract(DateTime.Now).TotalMilliseconds > 0)
            {
                try
                {
                    action();
                    //no error - return successfully:
                    return;
                }
                catch (AssertFailedException aEx)
                {
                    ex = aEx;
                    Thread.Sleep(retryIntervalMilliseconds);
                }
            }
            throw ex;
        }
コード例 #24
0
        public void ValidaCuraFeitaPersonagemParaOutroSemSucesso()
        {
            string _nameFaction      = "Warriors";
            string _otherNameFaction = "Raptors";

            _character.JoinFaction(new AbsFaction(_nameFaction));

            string otherName = "OtherPerson";

            var _otherCharacter = new Character()
            {
                Name = otherName
            };

            _otherCharacter.JoinFaction(new AbsFaction(_otherNameFaction));

            var serviceCharacter = new ServiceCharacter(_character);

            var _newHealth = 1000;

            _character.UpHealth(_newHealth);

            try
            {
                serviceCharacter.BeCure(_otherCharacter);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "A character can only heal characters of his own faction.");

                _character.DownHealth(_newHealth);

                Assert.AreEqual(_character.Health, _originalHealt);
                Assert.AreEqual(_character.Level, _originalLevel);
                Assert.AreEqual(_character.Alive, true);
                Assert.AreNotEqual(_character.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #25
0
        internal static Exception BuildThrowsException(Exception ex, string message)
        {
            PreserveStackTrace(ex);
            Exception result = new AssertFailedException("Assert.Throws() failure: " + message + "\r\n" + ex.Message);

            FieldInfo remoteStackTraceString = typeof(Exception)
                                               .GetField("_remoteStackTraceString",
                                                         BindingFlags.Instance | BindingFlags.NonPublic);

            string currentMethod = MethodBase.GetCurrentMethod().Name;
            string stackTrace    = String.Join(Environment.NewLine,
                                               ex.StackTrace
                                               .Split(new[]
            {
                Environment.NewLine
            }, StringSplitOptions.RemoveEmptyEntries)
                                               .Distinct()
                                               .Where(frame => !frame.Contains(currentMethod))
                                               .ToArray());

            remoteStackTraceString.SetValue(
                result,
                stackTrace + Environment.NewLine);

            // Roundtrip via serialization to cause the full exception data to be persisted,
            // and to cause the remote stacktrace to be cleaned-up.
            var selector  = new ExceptionSurrogateSelector();
            var formatter = new BinaryFormatter(selector, new StreamingContext(StreamingContextStates.All));

            using (var mem = new MemoryStream())
            {
                formatter.Serialize(mem, result);
                mem.Position = 0;
                result       = (Exception)formatter.Deserialize(mem);
                PreserveStackTrace(result);
            }

            return(result);
        }
コード例 #26
0
        public void ValidaAtaqueFeitoAUmObjetoSemSucesso()
        {
            var _potenciaAtaque = 10;

            var _object = new Objects(_originalHealt);

            _object.DownHealth(_originalHealt);

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.MakeAttack(_potenciaAtaque, _object);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "Object is already destroyed.");

                Assert.AreEqual(_object.Destroyed, true);
            }
        }
コード例 #27
0
        public void ValidaAtaqueSofridoPersonagemPeloMesmoPersonagem()
        {
            var _potenciaAtaque = 10;

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.GetAttack(_potenciaAtaque, _character);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "You cant attack yourself.");

                Assert.AreEqual(_character.Health, _originalHealt);
                Assert.AreEqual(_character.Level, _originalLevel);
                Assert.AreEqual(_character.Alive, true);
                Assert.AreNotEqual(_character.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #28
0
        public void ValidaAtaqueFeitoPersonagemContraOutroPersonagemDiferenteFacao()
        {
            string _nameFaction      = "Warriors";
            string _otherNameFaction = "Raptors";

            _character.JoinFaction(new AbsFaction(_nameFaction));

            string otherName       = "OtherPerson";
            var    _potenciaAtaque = 10;

            var _otherCharacter = new Character()
            {
                Name = otherName
            };

            _otherCharacter.JoinFaction(new AbsFaction(_nameFaction));
            _otherCharacter.JoinFaction(new AbsFaction(_otherNameFaction));

            _otherCharacter.LeaveFaction(new AbsFaction(_otherNameFaction));

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.MakeAttack(_potenciaAtaque, _otherCharacter);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "You cant attack yours allies.");
                Assert.AreEqual(_otherCharacter.Health, _originalHealt);
                Assert.AreEqual(_otherCharacter.Level, _originalLevel);
                Assert.AreEqual(_otherCharacter.Alive, true);
                Assert.AreNotEqual(_otherCharacter.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
                Assert.AreEqual(_otherCharacter.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #29
0
        public void ValidaAtaqueFeitoPersonagemContraOMesmoPersonagem()
        {
            var _otherCharacter = new Character();

            var serviceCharacter = new ServiceCharacter(_character);
            var _potenciaAtaque  = 10;

            try
            {
                serviceCharacter.MakeAttack(_potenciaAtaque, _character);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "You cant attack yourself.");

                Assert.AreEqual(_character.Health, 1000);
                Assert.AreEqual(_character.Level, 1);
                Assert.AreEqual(_character.Alive, true);
                Assert.AreNotEqual(_character.Alive, false);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }
コード例 #30
0
        public void ValidaCuraFeitaPeloProprioPersonagemQueEstaMortoComErro()
        {
            var _newHealth = 1000;

            _character.DownHealth(_newHealth);

            var serviceCharacter = new ServiceCharacter(_character);

            try
            {
                serviceCharacter.BeCure(_character);
            }
            catch (Exception ex)
            {
                Assert.IsNotNull(ex);
                AssertFailedException.Equals(ex.Message, "We cant cure a dead character.");

                Assert.AreEqual(_character.Health, 0);
                Assert.AreEqual(_character.Level, 0);
                Assert.AreEqual(_character.Alive, false);
                Assert.AreNotEqual(_character.Alive, true);
                Assert.AreEqual(_character.KindOfFighter, TypeOfFighter.Melee);
            }
        }