Beispiel #1
0
        public void StaticAccessorForStubAll()
        {
            ICat cat = MockRepository.Mock <ICat>();

            cat.Eyes = 2;
            Assert.Equal(2, cat.Eyes);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Pet    thisPet;
            Dog    dog  = new Dog();
            Cat    cat  = new Cat();
            IDog   iDog = new IDog();
            ICat   iCat = new ICat();
            Pets   pets = new Pets();
            Random rand = new Random();

            for (int x = 0; x > 51; x++)
            {
                if (rand.Next(1, 11) == 1)
                {
                    // 50% chance of adding a dog
                    if (rand.Next(0, 2) == 0)
                    {
                        dog.Add(dog);
                    }
                    else
                    {
                        // else add a cat
                        cat.Add(cat);
                    }
                }
                else
                {
                    thisPet = pets.petList;
                }
            }
        }
Beispiel #3
0
        public void Run()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <WhiteCat>().SingleInstance();  //注册成单例模式
            builder.RegisterType <BlackCat>();
            builder.RegisterType <WhiteCat>().As <ICat>();

            using (var container = builder.Build())
            {
                ICat wcat = container.Resolve <WhiteCat>();
                ICat bcat = container.Resolve <BlackCat>();

                if (wcat == bcat && Object.ReferenceEquals(wcat, bcat))
                {
                    Console.WriteLine("两只一样的猫");
                }
                else
                {
                    Console.WriteLine("两只不一样的猫");
                }

                var myCat = container.Resolve <ICat>();
                myCat.Run();
            }
        }
        static void Main(string[] args)
        {
            // Autofac container.
            var builder = new ContainerBuilder();

            builder.RegisterType <Cat>().As <ICat>();

            // Create Logger<T> when ILogger<T> is required.
            builder.RegisterGeneric(typeof(Logger <>)).As(typeof(ILogger <>));

            // Use NLogLoggerFactory as a factory required by Logger<T>.
            builder.RegisterType <NLogLoggerFactory>().AsImplementedInterfaces().InstancePerLifetimeScope();

            // Finish registrations and prepare the container that can resolve things.
            var container = builder.Build();

            // Entry point. This provides our logger instance to a Cat's constructor.
            ICat cat = container.Resolve <ICat>();

            // Run
            string result = cat.MakeSound();

            Console.WriteLine(result);
            Console.ReadKey();
        }
        private void OnAddCat(ICatData catData)
        {
            ICat cat = catsFabric.Create(catData, mouse.speed, cellData.difficult.coefficient);

            catsOnCell.AddCat(cat);
            catData.SetFree(false);
            cellWindow.SetCatsInfo(catsOnCell.GetCats());
        }
        public void StaticAccessorForStubAll()
        {
            ICat cat = MockRepository.Mock <ICat>();

            cat.SetUnexpectedBehavior(UnexpectedCallBehaviors.BaseOrDefault);

            cat.Eyes = 2;
            Assert.Equal(2, cat.Eyes);
        }
Beispiel #7
0
        public void GetInterfaceCreator()
        {
            locator.Register <ICat>(delegate() { return(new Cat(new Owner(), "Ashley")); });
            ICat cat = locator.Get <ICat>();

            Assert.IsNotNull(cat);
            Assert.IsTrue(cat is Cat);
            Assert.AreEqual("Ashley", cat.Name);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            ICat cat   = new Cat("Tom");
            ICat proxy = LoggingProxy.CreateInstance(cat);

            proxy.eat();
            proxy.Name = "Jerry";
            proxy.Name = "Cookie";
        }
Beispiel #9
0
        public void GetInterfaceSingleton()
        {
            Cat ashley = new Cat(new Owner(), "Ashley");

            locator.Register <ICat>(ashley);
            ICat cat = locator.Get <ICat>();

            Assert.AreSame(ashley, cat);
        }
Beispiel #10
0
        public IActionResult TeddyToys()
        {
            //Fabric2
            IToysFactory toyFactor = new TeddyToysFactory();
            IBear        bear      = toyFactor.GetBear();
            ICat         cat       = toyFactor.GetCat();

            ViewData["result"] = $"{bear.Message} {cat.Message }";
            return(View());
        }
Beispiel #11
0
        public IActionResult WoodenToys()
        {
            //Fabric1
            IToysFactory toyFactory = new WoodenToysFactory();
            IBear        bear       = toyFactory.GetBear();
            ICat         cat        = toyFactory.GetCat();

            ViewData["result"] = $"{bear.Message} {cat.Message }";
            return(View());
        }
Beispiel #12
0
        //Client call this
        static void CreatedAndAttack(IFactory factory)
        {
            IBird b = factory.makeBird();

            b.attack();

            ICat c = factory.makeCat();

            c.attack();
        }
Beispiel #13
0
        public CatBuilderContext(ICat cat, Type serviceType, string registrationName = null)
        {
            this.Cat = cat;
            this.ServiceType = serviceType;
            this.RegistrationName = registrationName;
            this.Properties = new Dictionary<string, object>();
            this.BuilderKey = new NamedType(this.RegistrationName, this.ServiceType);

            CatRegistration registration;
            this.Registration = this.Cat.Registrations.TryGetValue(this.BuilderKey, out registration) ? registration : null;
        }
Beispiel #14
0
        public void DemoStubAllLegsProperty()
        {
            ICat catStub = MockRepository.Mock <ICat>();

            catStub.Legs = 0;
            Assert.Equal(0, catStub.Legs);

            SomeClass instance = new SomeClass(catStub);

            instance.SetLegs(10);
            Assert.Equal(10, catStub.Legs);
        }
Beispiel #15
0
        public void GetInterfaceDependentParameterizedCtor()
        {
            locator.Register <ICat>(typeof(Cat), typeof(IOwner));
            locator.Register <IOwner>(typeof(Owner));

            ICat instance = locator.Get <ICat>();

            Assert.IsNotNull(instance);
            Assert.IsTrue(instance is Cat);
            Assert.IsNotNull(instance.Owner);
            Assert.IsTrue(instance.Owner is Owner);
        }
Beispiel #16
0
        public void GetInterfaceMixedParameterizedCtor()
        {
            locator.Register <IOwner>(typeof(Owner));
            locator.Register <ICat>(typeof(Cat), new TypeParameter(typeof(IOwner)), new TypeParameter(typeof(string), "Kitty"));
            ICat cat = locator.Get <ICat>();

            Assert.IsNotNull(cat);
            Assert.IsTrue(cat is Cat);
            Assert.IsNotNull(cat.Owner);
            Assert.IsTrue(cat.Owner is Owner);
            Assert.AreEqual(cat.Name, "Kitty");
        }
Beispiel #17
0
        public void CallingMethodOnStubAllDoesNotCreateExpectations()
        {
            ICat cat = MockRepository.Mock <ICat>();

            cat.Legs       = 4;
            cat.Name       = "Esther";
            cat.Species    = "Ordinary housecat";
            cat.IsDeclawed = true;

            cat.Stub(x => x.GetMood());

            cat.VerifyAllExpectations();
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            // Making a few cats and treating them as ICat
            // This is good for a demonstration, but in real life generally you won't do this
            ICat fatCat   = new FatCat();
            ICat shortCat = new ShortCat();

            fatCat.Meow();
            shortCat.Meow();

            // Since we know we have a fat cat, we can use our fat cat printer
            FatCat castFatCat = fatCat as FatCat;

            FatCatPrinter.Print(castFatCat);

            // What happens if we cast our ShortCat as a FatCat?
            FatCat castShortCat = shortCat as FatCat;

            FatCatPrinter.Print(castShortCat);

            // What would happen if we didn't use the "as" keyword?
            // FatCatPrinter.Print((FatCat)shortCat);

            // What's the advantage of using "as" ?
            // We can do null checks
            //FatCat castShortCat2 = shortCat as FatCat;
            //if (castShortCat2 != null)
            //    FatCatPrinter.Print(castShortCat2);

            // The "is" keyword is similar to as, but only returns true/false
            if (shortCat is FatCat)
            {
                FatCatPrinter.Print((FatCat)shortCat);
            }

            Console.WriteLine("---");
            Console.WriteLine("--- Now using factory ---");
            Console.WriteLine("---");

            // More realistic example of getting cats
            ICat catFromFactory1 = CatFactory.GetCat();
            ICat catFromFactory2 = CatFactory.GetCat();

            catFromFactory1.Meow();
            catFromFactory2.Meow();

            // Assignment
            //
            // todo: Use both keywords "as" and "is" to safely call the FatCatPrinter.Print method
            //
        }
Beispiel #19
0
        public static void Main()
        {
            var catType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.Name == nameof(Cat));

            // Create instance by calling the constructor method
            ConstructorInfo constructorToInvoke = catType.GetConstructor(new Type[] { typeof(string), typeof(int) });

            object[] constructorParameters = new object[] { "Gergan", 10 };
            ICat     catInstance           = constructorToInvoke.Invoke(constructorParameters) as ICat;

            Console.WriteLine(catInstance);
            Console.WriteLine(new string('=', 60));

            // Create instance with Activator.CreateInstance
            object[] parameters            = new object[] { "Stoycho", 1 };
            ICat     instanceWithActivator = Activator.CreateInstance(typeof(Cat), parameters) as ICat;

            Console.WriteLine(instanceWithActivator);
            Console.WriteLine(new string('=', 60));

            // Invoke Eat method
            var cat       = new Cat("Stamat", 7);
            var eatMethod = cat.GetType().GetMethod("Eat", BindingFlags.Public | BindingFlags.Instance);

            Console.WriteLine(eatMethod.Invoke(cat, new object[] { "Fish" }));
            Console.WriteLine(new string('=', 60));

            // Work with get and set
            var catNameProperty = cat.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
            var catName         = catNameProperty.GetMethod.Invoke(cat, new object[] { });

            Console.WriteLine($"The name of the cat is: {catName}");

            var catAgeProperty = cat.GetType().GetProperty("Age", BindingFlags.Public | BindingFlags.Instance);
            var originalCatAge = cat.Age;

            catAgeProperty.SetMethod.Invoke(cat, new object[] { 100 });
            Console.WriteLine($"Original age -> {originalCatAge}, Changed age -> {cat.Age}");

            // Work with get and set with methods
            catNameProperty = cat.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
            catName         = catNameProperty.GetValue(cat);
            Console.WriteLine($"Cat name: {catName}");

            catAgeProperty = cat.GetType().GetProperty("Age", BindingFlags.Public | BindingFlags.Instance);
            var anotherOriginalAge = cat.Age;

            catAgeProperty.SetValue(cat, 345);
            Console.WriteLine($"Original age -> {anotherOriginalAge}, Changed age -> {cat.Age}");
        }
        public void DemoStubAllLegsProperty()
        {
            ICat catStub = MockRepository.Mock <ICat>();

            catStub.SetUnexpectedBehavior(UnexpectedCallBehaviors.BaseOrDefault);

            catStub.Legs = 0;
            Assert.Equal(0, catStub.Legs);

            SomeClass instance = new SomeClass(catStub);

            instance.SetLegs(10);
            Assert.Equal(10, catStub.Legs);
        }
Beispiel #21
0
        public void StubAllCanCreateExpectationOnMethod()
        {
            ICat cat = MockRepository.Mock <ICat>();

            cat.Legs       = 4;
            cat.Name       = "Esther";
            cat.Species    = "Ordinary housecat";
            cat.IsDeclawed = true;

            cat.Stub(x => x.GetMood())
            .Return("Happy");

            Assert.Equal("Happy", cat.GetMood());
            cat.VerifyAllExpectations();
        }
Beispiel #22
0
        public void CallingMethodOnStubAllDoesNotCreateExpectations()
        {
            MockRepository mocks = new MockRepository();
            ICat           cat   = mocks.Stub <ICat>();

            using (mocks.Record())
            {
                cat.Legs       = 4;
                cat.Name       = "Esther";
                cat.Species    = "Ordinary housecat";
                cat.IsDeclawed = true;
                cat.GetMood();
            }
            mocks.VerifyAll();
        }
Beispiel #23
0
 public Program(
     ICat cat,
     IBox <ICat> box,
     IBox <IBox <ICat> > bigBox,
     Func <IBox <ICat> > func,
     Task <IBox <ICat> > task,
     Tuple <IBox <ICat>, ICat, IBox <IBox <ICat> > > tuple,
     Lazy <IBox <ICat> > lazy,
     IEnumerable <IBox <ICat> > enumerable,
     IBox <ICat>[] array,
     IList <IBox <ICat> > list,
     ISet <IBox <ICat> > set,
     IObservable <IBox <ICat> > observable,
     IBox <Lazy <Func <IEnumerable <IBox <ICat> > > > > complex,
     ThreadLocal <IBox <ICat> > threadLocal,
     ValueTask <IBox <ICat> > valueTask,
     (IBox <ICat> box, ICat cat, IBox <IBox <ICat> > bigBox) valueTuple)
Beispiel #24
0
        public void MethodResolving()
        {
            // Check if the method resolver works correctly
            IAnimal animal = null;
            ICat    cat    = null;
            IDog    dog    = null;


            // - Non-generic MethodInfo, ConstructorInfo
            {
                var ctor = GetCtor(() => new Internals());
                TestDeepEquality(ctor);

                var mAA = GetMethod(() => HandleAnimal(animal, animal));
                TestDeepEquality(mAA);

                var mCA = GetMethod(() => HandleAnimal(cat, animal));
                TestDeepEquality(mCA);

                var mAC = GetMethod(() => HandleAnimal(animal, cat));
                TestDeepEquality(mAC);

                var mCC = GetMethod(() => HandleAnimal(cat, cat));
                TestDeepEquality(mCC);
            }


            // - Simple closed generic
            {
                var mt = GetMethod(() => HandleAnimal(dog, dog));
                TestDeepEquality(mt);
            }

            // - Exception on open method
            {
                var open = GetMethod(() => HandleAnimal(dog, dog)).GetGenericMethodDefinition();
                try
                {
                    Clone(open);
                    throw new Exception("expected exception not thrown");
                }
                catch
                {
                }
            }
        }
Beispiel #25
0
        public void StubAllHasPropertyBehaviorForAllProperties()
        {
            ICat cat = MockRepository.Mock <ICat>();

            cat.Legs = 4;
            Assert.Equal(4, cat.Legs);

            cat.Name = "Esther";
            Assert.Equal("Esther", cat.Name);

            Assert.Null(cat.Species);
            cat.Species = "Ordinary housecat";
            Assert.Equal("Ordinary housecat", cat.Species);

            cat.IsDeclawed = true;
            Assert.True(cat.IsDeclawed);
        }
Beispiel #26
0
        public void ShouldBeThrowAnExpecificExceptionSettedOnGetByIdMethod()
        {
            ICat cat = ObjectIdentifier.Get <ICat>(new { Identifier = 1 });

            Assert.NotNull(cat);
            Assert.IsInstanceOf <ICat>(cat);
            var name = string.Empty;

            Assert.Throws(
                Is.
                InstanceOf <ExpecificException>(),
                () =>
            {
                name = cat.Name;
            }
                );
        }
Beispiel #27
0
        public void StubAllCanCreateExpectationOnMethod()
        {
            MockRepository mocks = new MockRepository();
            ICat           cat   = mocks.Stub <ICat>();

            using (mocks.Record())
            {
                cat.Legs       = 4;
                cat.Name       = "Esther";
                cat.Species    = "Ordinary housecat";
                cat.IsDeclawed = true;
                cat.GetMood();
                LastCall.Return("Happy");
            }
            Assert.Equal("Happy", cat.GetMood());
            mocks.VerifyAll();
        }
Beispiel #28
0
        public void StubAllCanRegisterToEventsAndRaiseThem()
        {
            MockRepository mocks = new MockRepository();
            ICat           cat   = mocks.Stub <ICat>();

            cat.Hungry += null;             //Note, no expectation!
            IEventRaiser eventRaiser = LastCall.GetEventRaiser();

            bool raised = false;

            cat.Hungry += delegate
            {
                raised = true;
            };

            eventRaiser.Raise(cat, EventArgs.Empty);
            Assert.True(raised);
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            RunCatProxy();

            ContainerBuilder builder = new ContainerBuilder();

            //先将拦截器注册到容器中。
            builder.RegisterType <CatInterceptor>();
            builder.RegisterType <CatOwnerInterceptor>();

            //将ICat、Cat注册到容器中,并增加拦截器,CatInterceptor,以接口形式设置拦截, 三种方式作用相同
            builder.RegisterType <Cat1>().As <ICat>().Named <ICat>("cat1").InterceptedBy(typeof(CatInterceptor)).EnableInterfaceInterceptors();
            builder.RegisterType <Cat2>().InterceptedBy(typeof(CatInterceptor)).EnableClassInterceptors();
            builder.RegisterType <Cat3>().As <ICat>().Named <ICat>("cat3").EnableInterfaceInterceptors();


            ///给铲屎官这个类,增加一个拦截器,并启用类拦截器,并注册ICat接口
            builder.RegisterType <CatOwner>().InterceptedBy(typeof(CatOwnerInterceptor)).EnableClassInterceptors(ProxyGenerationOptions.Default, additionalInterfaces: typeof(ICat));

            var container = builder.Build();


            ICat cat1 = container.ResolveNamed <ICat>("cat1");

            cat1.Eat();

            Cat2 cat2 = container.Resolve <Cat2>();

            cat2.Eat();

            ICat cat3 = container.ResolveNamed <ICat>("cat3");

            cat3.Eat();


            CatOwner catOwner = container.Resolve <CatOwner>();

            ///通过反射获取代理类CatOwner中的Eat方法,然后执行Eat方法, 但这个是会报错的,NotImplementedException
            catOwner.GetType().GetMethod("Eat").Invoke(catOwner, null);



            Console.ReadKey();
        }
Beispiel #30
0
 public bool Equals(ICat comparable)
 {
     return comparable != null && Name == comparable.Name;
 }
Beispiel #31
0
 /// <summary>
 /// Extension method to let cat play
 /// </summary>
 /// <param name="icat">Cat</param>
 /// <param name="toy">Something to play</param>
 public static void Play(this ICat icat, string toy) { }
Beispiel #32
0
 /// <summary>
 /// Extension method hint that how long the cat can sleep.
 /// </summary>
 /// <param name="icat">The type will be extended.</param>
 /// <param name="hours">The length of sleep.</param>
 public static void Sleep(this ICat icat, long hours) { }
Beispiel #33
0
 public void AddCat(ICat aCat)
 {
     _cats.Add(aCat);
 }
Beispiel #34
0
 public Cat(ICat parent = null)
 {
     this.Builders = new List<ICatBuilder>();
     this.Registrations = new Dictionary<NamedType, CatRegistration>();
     this.Parent = parent;
 }