Ejemplo n.º 1
0
        public void DeleteMethodTest()
        {
            var httpconfiguration = new HttpConfiguration();

            WebApiConfig.Register(httpconfiguration);
            var httpRouteData = new HttpRouteData(httpconfiguration.Routes["DefaultApi"],
                                                  new HttpRouteValueDictionary
            {
                { "controller", "Cars" }
            });
            var controller = new CarsController()
            {
                Request = new HttpRequestMessage(HttpMethod.Delete, "http://localhost:6664/api/cars")
                {
                    Properties =
                    {
                        {
                            HttpPropertyKeys.HttpConfigurationKey, httpconfiguration
                        },
                        {
                            HttpPropertyKeys.HttpRouteDataKey, httpRouteData
                        },
                    }
                }
            };


            var response = controller.Delete(22);

            //var response2 = controller.GetbyId(2);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); // if it finds a car with that id then it deletes and compares status code which is
                                                                     //OK with the returned status code which should be OK since it has deleted it succesfully

            //var car2 = response.Content.ReadAsAsync<Car>().Result;
            //var car = response2.Content.ReadAsAsync<Car>().Result;
            //Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            //Assert.AreEqual(HttpStatusCode.NotFound , response2.StatusCode);
        }
Ejemplo n.º 2
0
        public async void Delete_DeleteExistCar_CarHasBeenDeleted()
        {
            //Arrange
            var controller          = new CarsController(_carRepository);
            var exceptedName        = "car1";
            var exceptedDescription = "desc1";

            await CreateCar(exceptedName, exceptedDescription);

            var exceptedName2        = "car2";
            var exceptedDescription2 = "desc2";

            await CreateCar(exceptedName2, exceptedDescription2);

            //Act
            await controller.Delete(1);

            //Assert
            var listOfCars = await _carRepository.Get();

            listOfCars.Count().Should().Be(1);
        }
Ejemplo n.º 3
0
        public void PutTest()
        {
            var controller = new CarsController()
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };

            var car = new Car()
            {
                Id = 1, model = "new model", make = "new make"
            };
            var response = controller.Put(car.Id, car);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            var newCar = response.Content.ReadAsAsync <Car>().Result;

            Assert.AreEqual("new model", newCar.model);
            Assert.AreEqual("new make", newCar.make);
        }
Ejemplo n.º 4
0
        public void TestEditConfirmCar()
        {
            var car =
                new Car
            {
                CarId = 4,
                Model = "Ford",
                Vin   = "ansmdkesndh",
                Yop   = 1998,
            };
            var context = new Mock <ICarContex>();

            context.Setup(a => a.FindCarById(4)).Returns(car);
            context.Setup(s => s.SaveChanges()).Returns(0);
            var controller = new CarsController(context.Object);

            car.Model = "Opel";
            car.Vin   = "mdjsnrufkdsin";
            var result = controller.EditConfirm(car) as RedirectToRouteResult;

            Assert.AreEqual("Index", result.RouteValues["Action"]);
        }
Ejemplo n.º 5
0
        public void Add_ShouldAccessICarsRepositoryAddMethod()
        {
            // Arrange
            var car = new Car();

            car.Make  = "Mazda";
            car.Model = "MX-7";
            car.Id    = 1;

            var fakeCarRepo = new Mock <ICarsRepository>();

            fakeCarRepo.Setup(z => z.GetById(It.IsAny <int>())).Returns(car);
            fakeCarRepo.Setup(z => z.Add(It.IsAny <Car>()));

            var controller = new CarsController(fakeCarRepo.Object);

            // Act
            var actual = controller.Add(car);

            // Assert
            fakeCarRepo.Verify(repo => repo.Add(It.IsAny <Car>()), Times.Exactly(1));
        }
Ejemplo n.º 6
0
        private void ListCars_Load(object sender, EventArgs e)
        {
            DataGridViewTextBoxColumn brand = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn model = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn price = new DataGridViewTextBoxColumn();
            DataGridViewImageColumn   image = new DataGridViewImageColumn();

            dataGridView1.Columns.Add(brand);
            dataGridView1.Columns.Add(model);
            dataGridView1.Columns.Add(price);
            dataGridView1.Columns.Add(image);

            brand.HeaderText = "Marka";
            model.HeaderText = "Model";
            price.HeaderText = "Günlük Fiyat";
            image.HeaderText = "Resim";

            CarsController carsController = new CarsController();
            DataTable      dt             = carsController.GetCar();

            dataGridView1.DataSource = dt;
        }
Ejemplo n.º 7
0
        public async Task AddDistinctCar2_Works()
        {
            var _logger = new Mock <ILogger <CarsController> >();
            var repo    = new Mock <ICarsRepository>();

            CarsController carsController = new CarsController(_logger.Object, repo.Object);

            repo.Setup(carsRepo => carsRepo.UnitOfWork.SaveChangesAsync(default(CancellationToken)))
            .Returns(Task.FromResult(1));

            var car = new Car(1, "A8", 1, 10, "https://audi.ru", "base64:");

            repo.Setup(carsRepo => carsRepo.Get(It.IsAny <Guid>()))
            .Returns(Task.FromResult(car));

            var actionResult = await carsController.PostCar(new CreateCarCommand
                                                            { BrandId = 2, ModelName = "A10", ChassisTypeId = 1, SeatsCount = 4, Url = "https://ya.ru", UrlImage = "base64:" });

            var result = actionResult as CreatedAtActionResult;


            Assert.Equal(result.StatusCode, (int)System.Net.HttpStatusCode.Created);
        }
Ejemplo n.º 8
0
        public async Task GetAll_ReturnsOkResult_WithCarsRepository()
        {
            #region Arrange
            var mockRepo = new Mock <ICarsRepository>();

            mockRepo.Setup(x => x.GetAll(null))
            .Returns(GetCars);
            #endregion

            #region Act
            var ctrl   = new CarsController(mockRepo.Object, null);
            var result = await ctrl.GetAllCars();

            #endregion

            #region Assert
            Assert.NotNull(result);

            var okResult = result.Should().BeOfType <OkObjectResult>().Subject;
            var cars     = okResult.Value.Should().BeAssignableTo <IEnumerable <Car> >().Subject;
            cars.Count().Should().Be(1);
            #endregion
        }
Ejemplo n.º 9
0
        public void TestEditConfirmNotValidCar()
        {
            var car =
                new Car
            {
                CarId = 4,
                Model = "Ford",
                Vin   = "ansmdkesndh",
                Yop   = 1998,
            };
            var context = new Mock <ICarContex>();

            context.Setup(a => a.FindCarById(4)).Returns(car);
            context.Setup(s => s.SaveChanges()).Returns(0);
            var carController = new CarsController(context.Object);

            car.Model = "Opel";
            car.Vin   = "dsin";
            carController.ViewData.ModelState.AddModelError("Vin", "Vin powinien mieć conajmniej 10 znaków");
            var result = (ViewResult)carController.EditConfirm(car);

            Assert.AreEqual("Edit", result.ViewName);
        }
Ejemplo n.º 10
0
        public async Task ValidateParameters_ShouldPass(int brand, string model, int chassis, int seats, string url, string urlImage)
        {
            var _logger = new Mock <ILogger <CarsController> >();

            CarsController carsController = new CarsController(
                //  _db,
                _logger.Object,
                new CarsRepository(_db));

            await carsController.PostCar(new CreateCarCommand
            {
                BrandId       = brand,
                ModelName     = model,
                ChassisTypeId = chassis,
                SeatsCount    = seats,
                Url           = url,
                UrlImage      = urlImage
            });

            Assert.Equal(2, _db.Cars.Count());

            Assert.Equal(1, _db.CarImages.Count());
        }
        public void UpdateStock_Should_Return_ValidResult()
        {
            //arrange
            var mockILogger       = new Mock <ILogger <CarsController> >();
            var mockCarManagement = new Mock <ICarManagement>();
            var mockValidation    = new Mock <IValidation>();
            var mockApiContext    = new Mock <ApiContext>(dbContextOptions);

            mockValidation.Setup(_ => _.ValidateIntParameter(It.IsAny <int>()))
            .Returns(true);
            mockValidation.Setup(_ => _.ValidateStringParameter(It.IsAny <string>()))
            .Returns(true);
            mockApiContext.Setup(_ => _.UpdateStock(It.IsAny <UpdateStockRequest>()))
            .Returns(new CarStock());

            var controller = new CarsController(mockApiContext.Object, mockCarManagement.Object, mockValidation.Object, mockILogger.Object);

            //act
            var result = controller.UpdateStock(new UpdateStockRequest());

            //assert
            result.Should().BeOfType(typeof(OkObjectResult));
        }
        public void SearchStock_Should_Return_ValidStock()
        {
            //arrange
            var mockILogger       = new Mock <ILogger <CarsController> >();
            var mockCarManagement = new Mock <ICarManagement>();
            var mockValidation    = new Mock <IValidation>();
            var mockApiContext    = new Mock <ApiContext>(dbContextOptions);

            mockValidation.Setup(_ => _.ValidateStringParameter(It.IsAny <string>()))
            .Returns(true);
            mockApiContext.Setup(_ => _.GetCars())
            .Returns(new List <CarStock>());
            mockCarManagement.Setup(_ => _.SearchStock(It.IsAny <List <CarStock> >(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(It.IsAny <SearchCarResponse>());

            var controller = new CarsController(mockApiContext.Object, mockCarManagement.Object, mockValidation.Object, mockILogger.Object);

            //act
            var result = controller.SearchStock(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>());

            //assert
            result.Should().BeOfType(typeof(OkObjectResult));
        }
Ejemplo n.º 13
0
        public void Details_CarReturnedByGetByIdIsNull_ShouldThrowTheCorrectMessage()
        {
            var actual = false;

            Car car = null;

            var fakeCarRepo = new Mock <ICarsRepository>();

            fakeCarRepo.Setup(cp => cp.GetById(It.IsAny <int>())).Returns(car);

            var controller = new CarsController(fakeCarRepo.Object);

            try
            {
                var result = controller.Details(100);
            }
            catch (ArgumentNullException ex)
            {
                actual = ex.Message.Contains("Car could not be found");
            }

            Assert.IsTrue(actual);
        }
Ejemplo n.º 14
0
        public void D_Edit_Car_RedirectToDetails()
        {
            // ARRANGE
            var carsController = new CarsController(carRepo);

            // ACT - Edit View calls EditCar method from CarController, which implements EditCar from ICarRepository (replacing the car at the id with a new car).
            var actionResult = carsController.Edit(1,
                                                   new Car
            {
                Id           = 1,
                Make         = "Toyota",
                Model        = "Corolla",
                Colour       = "Black",
                Year         = 2010,
                PurchaseDate = new DateTime(2015, 01, 15),
                Kilometres   = 109317
            });

            // ASSERT (check for redirection to Index)
            Assert.IsType <RedirectToActionResult>(actionResult);
            var redirectToActionResult = actionResult as RedirectToActionResult;

            Assert.Equal("Index", redirectToActionResult.ActionName);

            // ACT (again - for car Details)
            actionResult = carsController.Details(1);
            // ASSERT (again - for car Details)
            Assert.IsType <ViewResult>(actionResult);
            var viewResult = actionResult as ViewResult;

            Assert.IsType <Car>(viewResult.Model);
            var car = viewResult.Model as Car;

            // Test if edited changes persisted to the Index page after redirecting.
            Assert.Equal(109317, car.Kilometres);
            Assert.Equal("Black", car.Colour);
        }
Ejemplo n.º 15
0
        public async void GetAllCars()
        {
            //Arrange
            var databaseName   = Guid.NewGuid().ToString();
            var context        = BuildContext(databaseName);
            var mapper         = BuildMap();
            var carsRepository = new CarRepository(context);

            var carParams = new CarParams()
            {
                PageNumber = 1,
                PageSize   = 10
            };

            context.Cars.Add(new Car()
            {
            });
            context.Cars.Add(new Car()
            {
            });
            await context.SaveChangesAsync();

            //Act
            var testContext = BuildContext(databaseName);
            var controller  = new CarsController(
                carsRepository, mapper,
                null, testContext, null);

            controller.ControllerContext.HttpContext = new DefaultHttpContext();
            var response = await controller.GetCars(carParams);

            OkObjectResult okResult = response as OkObjectResult;
            var            cars     = (List <CarForListDto>)okResult.Value;

            //Assert
            Assert.Equal(2, (int)cars.Count);
        }
Ejemplo n.º 16
0
        public void TwoCarsIndexWorks()
        {
            //Arrange
            List <Car> cars = new List <Car> {
                new Car()
                {
                    Id = 1, Brand = "test1", Name = "tester1"
                },
                new Car()
                {
                    Id = 2, Brand = "test2", Name = "tester2"
                }
            };
            var carsController = new CarsController(new MockCarsRepository(cars));

            //Act
            var result = carsController.Index();

            //Assert
            var viewResult = Assert.IsType <ViewResult>(result);
            var model      = Assert.IsAssignableFrom <List <Car> >(viewResult.ViewData.Model);

            Assert.Equal(2, model.Count);
        }
Ejemplo n.º 17
0
        public async Task IfHasPowerWindowsAndLowMiles_ReturnsThreeCars()
        {
            //Arrange
            var carQueryOptions = new CarQueryOptions
            {
                HasHeatedSeats = true,
                HasNavigation  = false
            };
            var mockICarRepo = new Mock <ICarRepository>();
            var mockReturn   = new List <Car>()
            {
                new Car(), new Car(), new Car()
            };

            mockICarRepo.Setup(repo => repo.GetCars(carQueryOptions))
            .Returns(Task.FromResult <IEnumerable <Car> >(mockReturn));
            var carController = new CarsController(mockICarRepo.Object);

            //Act
            var result = await carController.GetCars(carQueryOptions);

            //Assert
            Assert.Equal(3, result.Count <Car>());
        }
Ejemplo n.º 18
0
        public async Task IfHasFrWheelDriveSunroofAndPowerWindows_ReturnsOneCars()
        {
            //Arrange
            var carQueryOptions = new CarQueryOptions
            {
                HasHeatedSeats = true,
                HasNavigation  = false
            };
            var mockICarRepo = new Mock <ICarRepository>();
            var mockReturn   = new List <Car>()
            {
                new Car()
            };

            mockICarRepo.Setup(repo => repo.GetCars(carQueryOptions))
            .Returns(Task.FromResult <IEnumerable <Car> >(mockReturn));
            var carController = new CarsController(mockICarRepo.Object);

            //Act
            var result = await carController.GetCars(carQueryOptions);

            //Assert
            Assert.Single(result);
        }
Ejemplo n.º 19
0
        public async Task Edit_Post_UpdateCar()
        {
            var car = new Car
            {
                Id     = 1,
                Model  = "model",
                Number = "number"
            };

            var context = MakeContext();
            await context.CarsDao.CreateAsync(car);

            var controller = new CarsController(context.CarsDao)
            {
                TempData          = context.TempDataDictionary,
                ControllerContext = context.ControllerContext
            };
            var vm = new EditViewModel
            {
                EditorMode = EditorMode.Update,
                Id         = 1,
                Model      = "model1",
                Number     = "number1",
                ReturnUrl  = "/"
            };

            var r = await controller.Edit(vm) as RedirectResult;

            Assert.NotNull(r);
            Assert.Equal(vm.ReturnUrl, r.Url);
            Assert.Single(context.Cars);
            var updatedCar = context.Cars.First();

            Assert.Equal(vm.Model, updatedCar.Model);
            Assert.Equal(vm.Number, updatedCar.Number);
        }
Ejemplo n.º 20
0
        public void C_Create_Car_RedirectsToIndex()
        {
            // ARRANGE
            var carsController = new CarsController(carRepo);

            // ACT
            var actionResult = carsController.Create(
                new Car
            {
                Id           = 6,
                Make         = "Dodge",
                Model        = "Viper",
                Colour       = "GTS-R Blue",
                Year         = 2018,
                PurchaseDate = new DateTime(2019, 06, 15),
                Kilometres   = 326
            });

            // ASSERT
            Assert.IsType <RedirectToActionResult>(actionResult);
            var redirectToActionResult = actionResult as RedirectToActionResult;

            Assert.Equal("Index", redirectToActionResult.ActionName);

            // ACT (again)
            actionResult = carsController.Index();
            // ASSERT (again)
            Assert.IsType <ViewResult>(actionResult);
            var viewResult = actionResult as ViewResult;

            Assert.IsType <List <Car> >(viewResult.Model);
            var cars = viewResult.Model as List <Car>;

            // Check that there are 6 cars on the Index page after redirecting.
            Assert.Equal(6, cars.Count);
        }
Ejemplo n.º 21
0
        public async void CanGetCar()
        {
            using (var context = new CarContext(ContextOptions))
            {
                var controller = new CarsController(context);

                // get all cars
                var enumerableCars = await controller.GetCars();

                List <Car> cars = enumerableCars.Value.ToList();

                // get a car
                var car = (await controller.GetCar(cars[0].Id)).Value;

                // test car attributes
                Assert.Equal("Nissan", car.Make);
                Assert.Equal(VehicleType.CAR, car.VehicleType);
                Assert.Equal("Juke 2020", car.Model);
                Assert.Equal("1.0-litre, three-cylinder turbo-petrol engine", car.Engine);
                Assert.Equal("SUV", car.BodyType);
                Assert.Equal(5, car.Doors);
                Assert.Equal(4, car.Wheels);
            }
        }
Ejemplo n.º 22
0
        public void B_Details_CarId_ReturnsCar()
        {
            // ARRANGE
            var carsController = new CarsController(carRepo);

            // ACT
            var actionResult = carsController.Details(4);

            // ASSERT
            Assert.IsType <ViewResult>(actionResult);
            var viewResult = actionResult as ViewResult;

            Assert.IsType <Car>(viewResult.Model);
            var car = viewResult.Model as Car;

            // Test all properties for the car corresponding to the actionResult.
            Assert.Equal(4, car.Id);
            Assert.Equal("Ferrari", car.Make);
            Assert.Equal("LaFerrari", car.Model);
            Assert.Equal("Ferrari Red", car.Colour);
            Assert.Equal(2018, car.Year);
            Assert.Equal(new DateTime(2020, 11, 07), car.PurchaseDate);
            Assert.Equal(87, car.Kilometres);
        }
Ejemplo n.º 23
0
        public void GetCarFromId()
        {
            // Arrange
            List <Car> fakeCollection = new List <Car>
            {
                new Car
                {
                    CarId       = "2",
                    CarName     = "BMW",
                    Description = "Скорость"
                }
            };
            var mock       = new MockMethodsCarsDBService(fakeCollection);
            var controller = new CarsController(mock);

            // Act
            var result = controller.Get("2");

            // Assert
            var viewResult = Assert.IsType <ActionResult <Car> >(result);

            Assert.IsAssignableFrom <Car>(viewResult.Value);
            Assert.Equal("BMW", viewResult.Value.CarName);
        }
 public void CreateController()
 {
     this.controller = new CarsController(this.carsData);
 }
 public void CreateController()
 {
     this.controller = new CarsController(this.carsData);
 }
Ejemplo n.º 26
0
 public CarBrainEvolution(CarsController carsController)
 {
     this.carsController = carsController;
 }
Ejemplo n.º 27
0
 public void CarsControllerShouldInstantiateWithDefaultRepoWithoutThrowing()
 {
     var carsController = new CarsController();
 }
Ejemplo n.º 28
0
        public void Sort_ShouldThrowArgumentException_WhenCalledWithInvalidString(string condition)
        {
            var controller = new CarsController();

            Assert.Throws <ArgumentException>(() => controller.Sort(condition));
        }
Ejemplo n.º 29
0
 public void Init()
 {
     controller = new CarsController();
 }
Ejemplo n.º 30
0
 public void TestInitialization()
 {
     //// Just to pass through empty constructor.
     this.controller = new CarsController();
     this.controller = new CarsController(this.fakeCarsData);
 }
Ejemplo n.º 31
0
        public void AddCar_ShouldThrowArgumentNullException_WhenCalledWithNull()
        {
            var controller = new CarsController();

            Assert.Throws <ArgumentNullException>(() => controller.Add(null));
        }