Exemplo n.º 1
0
        public void TestInterfaceProxyMethodVariance()
        {
            Duck       duck  = new Duck();
            IInterface proxy = DuckTyping.Cast <IInterface>(duck);

            string stringValue = "String value.";
            int    intValue    = 5;

            Assert.AreEqual(stringValue, proxy.ContravariantMethod(stringValue), "Contravariant method returned wrong value.");
            Assert.IsNull(proxy.ContravariantMethod(null), "Passing and returning a null value to and from a contravariant method failed.");

            try
            {
                proxy.ContravariantMethod(new object[0]);

                Assert.Fail("Passing a non-string object through a contravariant method that takes a string parameter should have thrown an InvalidCastException.");
            }
            catch (InvalidCastException)
            { }

            try
            {
                proxy.ContravariantValueMethod(7);

                Assert.Fail("Passing a non-DateTime object through a contravariant method that takes a DateTime parameter should have thrown an InvalidCastException.");
            }
            catch (InvalidCastException)
            { }

            try
            {
                proxy.ContravariantValueMethod(null);

                Assert.Fail("Passing null through a contravariant method that takes a value type parameter should have thrown a NullReferenceException.");
            }
            catch (NullReferenceException)
            { }

            Assert.AreEqual("Method", proxy.ContravariantEnumMethod("Method"), "Contravariant method returned wrong enum value.");

            try
            {
                proxy.ContravariantEnumMethod(null);

                Assert.Fail("Passing null through a contravariant method that taks an enum parameter should have thrown a NullReferenceException.");
            }
            catch (NullReferenceException)
            { }

            Assert.AreEqual(stringValue, proxy.CovariantMethod(stringValue), "Covariant method returned wrong value.");
            Assert.IsNull(null, proxy.CovariantMethod(null), "Passing and returning a null value to and from a covariant method failed.");
            Assert.AreEqual(intValue, proxy.CovariantValueMethod(intValue), "Covariant method returned wrong int value.");
            Assert.AreEqual(AttributeTargets.Class, proxy.CovariantEnumMethod(AttributeTargets.Class), "Covariant method returned wrong enum value.");

            // Note: This next line is primarily to check whether the system handles a recursive cast properly.  If it doesn't,
            // a StackOverflowException will be thrown.
            Assert.IsTrue(proxy.Equals(proxy.VariantByRecursiveCastMethod(duck)), "Variant by recursive cast method returned wrong value.");

            Assert.AreEqual(duck, proxy.VariantByUncastMethod(proxy), "Variant by uncast method returned wrong value.");
        }