Inheritance: Controller
        public void IndexAction()
        {
            // Arrange
            AutoMapperWebConfiguration.ConfigureWebMapping();
            var mockDataReader = new Mock<IDataReader>();
         var vmMock = new Mock<PostCodeResultVm>();
            vmMock.Object.Postcode = "RM1 3RL";
            PostCodeResult postCodeData = new PostCodeResult {};
            postCodeData.result = new Result
            {
                admin_county = "Essex",
                admin_district = "Romford",
                admin_ward = "Loxford",
                codes = new Codes() {admin_district = "11"}
            };
            mockDataReader.Setup(x => x.GetPostCodeResults(It.IsAny<String>())).ReturnsAsync(postCodeData);

            //Act
            var homeController = new HomeController(mockDataReader.Object);
            var indexView = homeController.Index(vmMock.Object);

            // Assert
            var result = indexView.Result as ViewResult;
            Assert.IsNotNull(result);
            var model = (PostCodeResultVm)result.Model;
            Assert.AreEqual(model.Codes.admin_district, "11");
            Assert.AreEqual(model.Admin_Ward, "Loxford");

        }
 public void SetUp()
 {
     Startup.ConfigureAutomapper();
     StackRepository = new Mock<IRepository<Stack>>();
     var costCalculator = new CostCalculator(new Mock<IRepository<Instance>>().Object, new Mock<IRepository<ResourceLedger>>().Object);
     HomeController = new HomeController(StackRepository.Object, null, null, null, null, null, Mapper.Engine, null, null, null, null, costCalculator, null);
 }
 public void Setup()
 {
     this.controller = new HomeController(this.ArticleServiceMock.Object)
     {
         Cache = this.CacheServiceMock.Object
     };
 }
        public void IndexTest()
        {
            var homeController = new HomeController();
            var actionResult = homeController.Index();

            Assert.NotNull(actionResult);
        }
Beispiel #5
0
            public void PullsDefaultFrontpage(whoaverseEntities db, Defaultsubverse defaultsubverse, List<Message> messages)
            {
                // Arrange
                // TODO: See if we can coax Autofixture into handling this for us
                if (defaultsubverse.name.Length > 20)
                    defaultsubverse.name = defaultsubverse.name.Substring(0, 19);
                db.Defaultsubverses.Add(defaultsubverse);
                db.Subverses.Add(new Subverse {name = defaultsubverse.name, title = new Guid().ToString()});
                db.SaveChanges();

                foreach (var message in messages)
                {
                    // TODO: See if we can coax Autofixture into handling this for us
                    if (message.Thumbnail.Length > 40)
                        message.Thumbnail = message.Thumbnail.Substring(0, 39);
                    message.Subverse = defaultsubverse.name;
                }
                db.Messages.AddRange(messages);
                db.SaveChanges();

                var homeController = new HomeController(db);
                homeController.ControllerContext = GetControllerContext(false);

                // Act
                var actionResult = (ViewResult) homeController.Index(null);
                var model = (PaginatedList<Message>) actionResult.Model;

                // Assert
                Assert.True(model.Count == messages.Count);
            }
        public void IndexPostTest()
        {
            var calcService = new CalcService();
            var controller = new HomeController();
            var model = new HomeModel();
            model.Number = "";
            ErrorTest(controller.Index(model) as PartialViewResult);

            model.Number = "asdf";
            ErrorTest(controller.Index(model) as PartialViewResult);

            model.Number = "-1";
            ErrorTest(controller.Index(model) as PartialViewResult);

            model.Number = "0";
            ErrorTest(controller.Index(model) as PartialViewResult);

            model.Number = "1.001";
            ErrorTest(controller.Index(model) as PartialViewResult);

            model.Number = "16";
            var result = controller.Index(model) as PartialViewResult;
            model = result.Model as HomeModel;
            Assert.IsNotNull(result);
            Assert.IsTrue(result.ViewData.ModelState.IsValid);
            Assert.AreEqual("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16", model.AllNumbers);
            Assert.AreEqual("1, 3, 5, 7, 9, 11, 13, 15", model.OddNumbers);
            Assert.AreEqual("2, 4, 6, 8, 10, 12, 14, 16", model.EvenNumbers);
            Assert.AreEqual("1, 2, C, 4, E, C, 7, 8, C, E, 11, C, 13, 14, Z, 16", model.SubstitutedNumbers);
            Assert.AreEqual("1, 1, 2, 3, 5, 8, 13", model.FibonacciNumbers);
        }
        public async void Register(UtsData data)
        {
            string json = JsonConvert.SerializeObject(data);
   
            Log.Info("Register", json);

           // Request Address of the API    
            string url = Server.url + "api/student/register";

           String result = null;
        
               using (WebClient wc = new WebClient())
               {
                
                wc.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
                wc.Headers.Add("AppKey", "66666");


                result = await wc.UploadStringTaskAsync(new Uri(url), json);
                   

                Log.Info("Register SUCCESS", result);
                HomeController loginController = new HomeController();
                await loginController.login(data.StudentId);

            }

              

        }
 public void Index()
 {
     var calculationService = new Mock<IPriceCalculationService>();
     var controller = new HomeController(calculationService.Object);
     var result = controller.Index().As<ViewResult>();
     result.Should().NotBeNull();
     result.Model.As<PriceCalculationViewModel>().Should().NotBeNull();
 }
        public void SetUp()
        {
            controller = new HomeController();

            filter = new AuthenticationFilter();

            PrepareController(controller);
        }
Beispiel #10
0
        public void DisplaysLoginScreenWhenCredentialsArentValid()
        {
            var credentials = new Credentials();
            var controller = new HomeController(null, null);

            controller.ModelState.AddModelError(string.Empty, string.Empty);
            MvcAssert.DefaultViewWithModel(credentials, controller.Login(credentials));
        }
        public void BeforeAll()
        {
            // Arrange
            var controller = new HomeController();

            // Act
            _result = controller.Index();
        }
        public void Setup()
        {
            // given
            _controller = new HomeController();

            // when
            _viewResult = _controller.Index() as ViewResult;
        }
Beispiel #13
0
 public void Index_action_returns_a_view()
 {
     //arrange
     var c = new HomeController();
     //act
     var i = c.Index();
     //assert
     Assert.AreEqual("testing2", "testing2", "Index view wrongly named");
 }
        public void Can_be_created()
        {
            var repository = Mock.Of<IPostRepository>();
            var validator = Mock.Of<ICodeValidator>();

            var target = new HomeController(repository, validator);

            Assert.NotNull(target);
        }
        public void ReturnsWithValidationErrors()
        {
            var user = new User();
            var controller = new HomeController(null, null);

            controller.ModelState.AddModelError(string.Empty, string.Empty);
            var result = controller.Register(user);
            MvcAssert.DefaultViewWithModel(user, result);
        }
        public new void Setup()
        {
            base.Setup();

            Services.Inject(new CategoryServiceStub(Categories));
            Services.Inject(new ProductServiceStub(Products));
            Controller = new HomeController(Services);
            Controller.ControllerContext = CreateContextMock();
        }
 public void AboutTest()
 {
     var calcService = new CalcService();
     var controller = new HomeController();
     var result = controller.About() as ViewResult;
     var message = result.ViewData["Message"].ToString();
     Assert.IsNotNull(result);
     Assert.AreEqual("How to use this calculator.", message);
 }
 public void Setup() {
     userService = MockRepository.GenerateStub<UserService>();
     homeController = new HomeController(userService);
     
     // setup a result for the getdata call
     userService.Stub(u => u.GetData<User, ExampleSiteDB>(i => i.IsActive == true))
         .IgnoreArguments()
         .Return(new List<User>());
 }
 public void ContactTest()
 {
     var calcService = new CalcService();
     var controller = new HomeController();
     var result = controller.Contact() as ViewResult;
     var message = result.ViewData["Message"].ToString();
     Assert.IsNotNull(result);
     Assert.AreEqual("My contact details.", message);
 }
        public void Index_Zero_Usuarios_Test()
        {
            IUserDataBase oUserDataBase = new UserDataBaseSTUB_0_usuarios();

            HomeController target = new HomeController(oUserDataBase);
            string expectedView = "NenhumRegistro";
            ViewResult resultado = (ViewResult)target.Index();
            Assert.AreEqual(expectedView, resultado.ViewName);
        }
Beispiel #21
0
        public void Default_Action_Returns_Index_View()
        {
            var homeController = new HomeController();

            var result = homeController.Index() as ViewResult;

            Assert.IsNotNull(result);
            Assert.IsNull(result.Model);
        }
        public void ExchangeGrid()
        {
            HomeController controller = new HomeController();
            //var exchange = controller.ExchangeGrid("test", "karl", 1, 3) as JsonResult;
            //var serializer = new JavaScriptSerializer();
            //var output = serializer.Serialize(exchange.Data);

            //Console.WriteLine(output);
        }
 public void AboutTest()
 {
     HomeController target = new HomeController(); // TODO: Initialize to an appropriate value
     ActionResult expected = null; // TODO: Initialize to an appropriate value
     ActionResult actual;
     actual = target.About();
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
 public HomeControllerTests()
 {
     WebSecurity = new Mock<IWebSecurity>(MockBehavior.Strict);
     SetUpContext();
     //Setup the fake security, repos, and db.
     UserRepository = new MockUserRepository(SocialContext, WebSecurity.Object, new PostRepository(SocialContext)
                                             , new GroupRepository(SocialContext));
     Controller = new HomeController(UserRepository);
 }
        public void Index_Um_Usuario_Test()
        {
            IUserDataBase oUserDataBase = new UserDataBaseSTUB_1_usuario();

            HomeController target = new HomeController(oUserDataBase);
            string expectedView = "AlgunsResultados";
            ViewResult resultado = (ViewResult)target.Index();
            Assert.AreEqual(expectedView, resultado.ViewName);
        }
 public void WhenUnableToResolveThenShouldContinueSilentlyTest()
 {
     // arrange
     var action = new HomeController().Action(e => e.Index());
     // act
     var controllerContext = action.Execute();
     // assert
     Assert.AreEqual("service is null", controllerContext.Controller.ViewBag.ServiceMessage);
 }
 public void CalculateCall()
 {
     var calculationService = new Mock<IPriceCalculationService>();
     var viewModel = new PriceCalculationViewModel { PlanType = PlanType.VoicePlan1 };
     calculationService.Setup(x => x.CalculatePrice(It.IsAny<PriceCalculationViewModel>())).Returns(new Price(10));
     var controller = new HomeController(calculationService.Object);
     var result = controller.CalculateCall(viewModel).As<PartialViewResult>();
     result.Should().NotBeNull();
     result.Model.As<Price>().Value.Should().Be(10);
 }
Beispiel #28
0
        public void About() {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.AreEqual("Your application description page.", result.ViewBag.Message);
        }
Beispiel #29
0
        public async void Index() {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = await controller.IndexAsync() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Beispiel #30
0
        public void Contact() {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Beispiel #31
0
        public void EditGet_ExistingIdPassed_ReturnsCorrectPerson()
        {
            var homeController = new HomeController(new PeopleList());
            var person         = new Person()
            {
                Id = 1, Name = "Test Testsson", PhoneNumber = "123456789", City = "Viborg"
            };

            var result = homeController.Edit(1);

            var viewResult = Assert.IsType <PartialViewResult>(result);
            var model      = Assert.IsAssignableFrom <Person>(viewResult.ViewData.Model);

            Assert.Equal(person.Id, model.Id);
            Assert.Equal(person.Name, model.Name);
            Assert.Equal(person.PhoneNumber, model.PhoneNumber);
            Assert.Equal(person.City, model.City);
        }
Beispiel #32
0
        public void   HomeControllerTests_Index_Test_Authenticated()
        {
            var context = new ControllerContext();

            context.HttpContext = new DefaultHttpContext
            {
                User = new GenericPrincipal(
                    new GenericIdentity("username"),
                    new string[0]
                    )
            };
            var controller = new HomeController
            {
                ControllerContext = context
            };

            controller.Index().Should().BeOfType(typeof(RedirectToActionResult));
        }
Beispiel #33
0
        public void Upload()
        {
            // Arrange
            HomeController controller      = new HomeController();
            var            httpContextMock = new Mock <HttpContextBase>();

            controller.ControllerContext = new ControllerContext(httpContextMock.Object, new RouteData(), controller);
            var FileUpload = new Mock <HttpPostedFileBase>();

            FileUpload.Setup(f => f.ContentLength).Returns(1);
            FileUpload.Setup(f => f.FileName).Returns("idsm_forupload.csv");

            // Act/
            ActionResult result = controller.Upload(FileUpload.Object);

            // Assert
            Assert.IsInstanceOf <ActionResult>(result);
        }
Beispiel #34
0
    /// <summary>
    /// Displays the loading bar and starts the login process
    /// </summary>
    private void ProcessLogin(HomeController controller)
    {
        if (!controller.ValidateTextFields())
        {
            return;
        }

        EditorUtility.DisplayProgressBar("Loading", "Logging In", .1f);

        if (controller.IsLoginSuccessful())
        {
            EditorUtility.DisplayProgressBar("Loading", "Initializing Platform", 0.4f);
            controller.ProcessStartUp();
        }

        EditorUtility.ClearProgressBar();
        GUIUtility.ExitGUI();
    }
        public void ControllerTest()
        {
            //Arrange
            var data = new[] { new Product {
                                   Name = "Test", Price = 100
                               } };
            var mock = new Mock <IRepository>();

            mock.SetupGet(m => m.Products).Returns(data);
            TypeBroker.SetTestOject(mock.Object);
            HomeController controller = new HomeController(mock.Object);

            //Act
            ViewResult result = controller.Index();

            //Assert
            Assert.Equal(data, result.ViewData.Model);
        }
Beispiel #36
0
        public void Index()
        {
            // Arrange
            var controller = new HomeController();

            // Act
            var result = (ViewResult)controller.Index();

            var mvcName = typeof(Controller).Assembly.GetName();
            var isMono  = Type.GetType("Mono.Runtime") != null;

            var expectedVersion = mvcName.Version.Major + "." + mvcName.Version.Minor;
            var expectedRuntime = isMono ? "Mono" : ".NET";

            // Assert
            Assert.AreEqual(expectedVersion, result.ViewData["Version"]);
            Assert.AreEqual(expectedRuntime, result.ViewData["Runtime"]);
        }
Beispiel #37
0
        public async Task Controller_Action_Should_Render_Correct_View()
        {
            // Arrange
            Mock <IService> mockService = new Mock <IService>();

            mockService.Setup(x => x.GetPetNameViewModel(PetType.Cat))
            .Returns(async() =>
            {
                await Task.Yield();
                return(_petCatNameViewModel);
            });
            // Act
            HomeController controller = new HomeController(mockService.Object);
            ViewResult     result     = await controller.Index() as ViewResult;

            // Assert
            Assert.AreEqual("Index", result.ViewName);
        }
        public void Users_HomeController_Index_ShouldReturnCorrectModel()
        {
            // Arrange
            var data           = new Mock <IUowData>();
            var pagerFactory   = new Mock <IPagerViewModelFactory>();
            var pagerViewModel = new Mock <IPagerViewModel>();

            data.Setup(d => d.Users.All()).Returns(UsersCollection().AsQueryable());
            pagerFactory.Setup(p => p.CreatePagerViewModel(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>())).Returns(pagerViewModel.Object);

            HomeController controller = new HomeController(data.Object, pagerFactory.Object);

            // Act
            var result = controller.Index() as ViewResult;

            // Assert
            Assert.IsInstanceOf <Tuple <IEnumerable <UserViewModel>, IPagerViewModel> >(result.Model);
        }
Beispiel #39
0
        public async Task Controller_Should_Return_ViewResult_With_Valid_Model()
        {
            // Arrange
            Mock <IService> mockService = new Mock <IService>();

            mockService.Setup(x => x.GetPetNameViewModel(PetType.Cat))
            .Returns(async() =>
            {
                await Task.Yield();
                return(_petCatNameViewModel);
            });
            // Act
            HomeController controller = new HomeController(mockService.Object);
            ViewResult     result     = await controller.Index() as ViewResult;

            // Assert
            Assert.IsInstanceOf <PetNameViewModel>(result.ViewData.Model);
        }
Beispiel #40
0
        public void Create_CreateNewPerson_ReturnsNewlyCreatedPerson()
        {
            var homeController = new HomeController(new PeopleList());
            var person         = new Person()
            {
                Name = "Micael Ståhl", PhoneNumber = "0725539574", City = "Vetlanda"
            };

            var result = homeController.Create(person);

            var viewResult = Assert.IsType <PartialViewResult>(result);
            var model      = Assert.IsAssignableFrom <Person>(viewResult.ViewData.Model);

            Assert.Equal(2, model.Id);
            Assert.Equal(person.Name, model.Name);
            Assert.Equal(person.City, model.City);
            Assert.Equal(person.PhoneNumber, model.PhoneNumber);
        }
Beispiel #41
0
        public void RepositoryPropertyCalledOnce()
        {
            // Arrange
            var mock = new Mock <IRepository>();

            mock.SetupGet(m => m.Products).Returns(new[] { new Product {
                                                               Name = "P1", Price = 100
                                                           } });
            var controller = new HomeController {
                Repository = mock.Object
            };

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

            // Assert
            mock.VerifyGet(m => m.Products, Times.Once);
        }
Beispiel #42
0
        public void IndexActionModelIsComplete(Product[] products)
        {
            // Arrange
            var mock = new Mock <IRepository>();

            mock.SetupGet(m => m.Products).Returns(products);
            var controller = new HomeController {
                Repository = mock.Object
            };

            // Act
            var model = (controller.Index() as ViewResult)?.ViewData.Model
                        as IEnumerable <Product>;

            // Assert
            Assert.Equal(controller.Repository.Products, model,
                         Comparer.Get <Product>((p1, p2) => p1.Name == p2.Name && p1.Price == p2.Price));
        }
Beispiel #43
0
        public void HomeController_Index_ShouldReturnCorrectThreads()
        {
            // Arrange
            var data             = new Mock <IUowData>();
            var viewModelFactory = new Mock <IViewModelFactory>();

            Mapper.Initialize(cfg => cfg.CreateMap <Thread, IndexPageThreadViewModel>());

            data.Setup(d => d.Threads.All()).Returns(ThreadsCollection().AsQueryable());

            HomeController controller = new HomeController(data.Object, viewModelFactory.Object);

            // Act
            ViewResult result = controller.Index() as ViewResult;

            // Assert
            viewModelFactory.Verify(v => v.CreateHomePageViewModel(It.Is <ICollection <IndexPageThreadViewModel> >(t => t.ElementAt(0).Id == 2), It.Is <ICollection <IndexPageThreadViewModel> >(t => t.ElementAt(0).Id == 1), It.Is <ICollection <IndexPageThreadViewModel> >(t => t.ElementAt(0).Id == 1)));
        }
        public void IndexActionModelIsComplete(Product[] products)
        {
            // Arrange
            var controller = new HomeController();

            controller.Repository = new ModelCompleteFakeRepository
            {
                Products = products
            };
            // Act
            var model = (controller.Index() as ViewResult)?.ViewData.Model
                        as IEnumerable <Product>;

            // Assert
            Assert.Equal(controller.Repository.Products, model,
                         Comparer.Get <Product>((p1, p2) => p1.Name == p2.Name &&
                                                p1.Price == p2.Price));
        }
Beispiel #45
0
        public void TestCorrectInput2()
        {
            HomeController controller = new HomeController();
            var            input      = new ViewModel()
            {
                Input = "[1,1,1,1,3,3,3,3,2,1,2,9,9,9]"
            };
            ViewResult result = controller.Index(input) as ViewResult;

            Assert.IsNotNull(result);

            var model = result.Model as ViewModel;

            Assert.IsNotNull(model);
            Assert.IsFalse(model.IsError);
            Assert.AreEqual("[1,1,1,1,3,3,3,3,2,1,2,9,9,9]", model.Input);
            Assert.AreEqual("[9,3,1]", model.Output);
        }
Beispiel #46
0
        public void PostRegistroIsOk()
        {
            var IUsuarioServiceMock      = new Mock <IUsuarioService>();
            var IAuthServiceMock         = new Mock <IAuthService>();
            var ISessionServiceMock      = new Mock <ISessionService>();
            var IValidacionUsuarioMock   = new Mock <IValidacionUsuario>();
            var IInmuebleServiceMock     = new Mock <IInmuebleService>();
            var IImageServiceMock        = new Mock <IImageService>();
            var IInmuebleTipoServiceMock = new Mock <IInmuebleTipoService>();
            var ICiudadServiceMock       = new Mock <ICiudadService>();

            var home = new HomeController(IUsuarioServiceMock.Object, IAuthServiceMock.Object, ISessionServiceMock.Object, IValidacionUsuarioMock.Object, IInmuebleServiceMock.Object, IImageServiceMock.Object, IInmuebleTipoServiceMock.Object, ICiudadServiceMock.Object);

            var user   = new UsuarioViewModel();
            var result = home.Registro(user);

            Assert.IsInstanceOf <RedirectToRouteResult>(result);
        }
Beispiel #47
0
        public void GetLoginIsOk()
        {
            var IUsuarioServiceMock      = new Mock <IUsuarioService>();
            var IAuthServiceMock         = new Mock <IAuthService>();
            var ISessionServiceMock      = new Mock <ISessionService>();
            var IValidacionUsuarioMock   = new Mock <IValidacionUsuario>();
            var IInmuebleServiceMock     = new Mock <IInmuebleService>();
            var IImageServiceMock        = new Mock <IImageService>();
            var IInmuebleTipoServiceMock = new Mock <IInmuebleTipoService>();
            var ICiudadServiceMock       = new Mock <ICiudadService>();

            var home = new HomeController(IUsuarioServiceMock.Object, IAuthServiceMock.Object, ISessionServiceMock.Object, IValidacionUsuarioMock.Object, IInmuebleServiceMock.Object, IImageServiceMock.Object, IInmuebleTipoServiceMock.Object, ICiudadServiceMock.Object);

            var user   = new UsuarioViewModel();
            var result = home.Login();

            Assert.IsInstanceOf <ViewResult>(result);
        }
Beispiel #48
0
        public void Can_Paginate()
        {
            // Arrange
            Mock <ICharacterRepository> mock = new Mock <ICharacterRepository>();

            mock.Setup(m => m.Characters).Returns(
                new Character[]
            {
                new Character {
                    Id = 1, Name = "P1"
                },
                new Character {
                    Id = 2, Name = "P2"
                },
                new Character {
                    Id = 3, Name = "P3"
                },
                new Character {
                    Id = 4, Name = "P4"
                },
                new Character {
                    Id = 5, Name = "P5"
                }
            }.AsQueryable());

            Mock <ICartProvider> cpMock = new Mock <ICartProvider>();

            cpMock.Setup(cp => cp.GetCart(It.IsAny <HomeController>())).Returns(new Cart()
            {
                Points = 1000
            });

            HomeController controller = new HomeController(mock.Object, cpMock.Object);

            controller.PageSize = 3;
            // Act
            var result = (CharactersListViewModel)controller.Index(2).Model;
            // Assert
            var prodArray = result.Characters.ToArray();

            Assert.IsTrue(prodArray.Length == 2);
            Assert.AreEqual(prodArray[0].Character.Name, "P4");
            Assert.AreEqual(prodArray[1].Character.Name, "P5");
        }
Beispiel #49
0
        public async Task MyPostStatus_Get()
        {
            var sourceBranch = new Branch {
                Id = 1, Name = "sourceBranch"
            };
            var destinationBranch = new Branch {
                Id = 1, Name = "destinationBranch"
            };
            var post = new Post
            {
                Id                = 1,
                PersonFrom        = "personFrom",
                PersonTo          = "personTo",
                AddressTo         = "addressTo",
                SourceBranch      = sourceBranch,
                DestinationBranch = destinationBranch,
                Branch            = sourceBranch,
                State             = PostState.Created
            };

            var mailDaoMock = new Mock <IMailDao>();

            mailDaoMock.Setup(m => m.GetByIdAsync(post.Id)).
            ReturnsAsync(post);

            var controller = new HomeController(mailDaoMock.Object);

            var r = await controller.MyPostStatus(post.Id) as ViewResult;

            Assert.NotNull(r);
            Assert.Null(r.ViewName);

            var vm = r.Model as MyPostStatusViewModel;

            Assert.NotNull(vm);
            Assert.Equal(post.Id, vm.PostId);
            Assert.Equal(post.PersonFrom, vm.PersonFrom);
            Assert.Equal(post.PersonTo, vm.PersonTo);
            Assert.Equal(post.AddressTo, vm.AddressTo);
            Assert.Equal(post.SourceBranch.Name, vm.SourceBranchName);
            Assert.Equal(post.DestinationBranch.Name, vm.DestinationBranchName);
            Assert.Equal(post.Branch.Name, vm.CurrentBranchName);
            Assert.Equal("Created", vm.PostState);
        }
Beispiel #50
0
        public void Register_GetView_ItsOkViewModelIsUserView()
        {
            AccountOwner owner7876Old;
            AccountOwner owner5678Old;

            using (TestDbContext context = new TestDbContext())
            {
                Account acc5678 = context.Accounts
                                  .Include(a => a.Owner).FirstOrDefault(a => a.Number == 5678);
                Account acc7876 = context.Accounts
                                  .Include(a => a.Owner).FirstOrDefault(a => a.Number == 7876);

                Assert.NotNull(acc7876, "Не найден счет с номером 7876");
                Assert.NotNull(acc5678, "Не найден счет с номером 5678");

                owner7876Old = acc7876.Owner;
                owner5678Old = acc5678.Owner;

                Assert.NotNull(owner7876Old, "Для счета с номером 7876 не указан владелец");
                Assert.NotNull(owner5678Old, "Для счета с номером 5678 не указан владелец");
            }

            var controller = new HomeController();
            var result     = controller.EditOwner();

            using (TestDbContext context = new TestDbContext())
            {
                Account acc5678 = context.Accounts
                                  .Include(a => a.Owner).FirstOrDefault(a => a.Number == 5678);
                Account acc7876 = context.Accounts
                                  .Include(a => a.Owner).FirstOrDefault(a => a.Number == 7876);

                AccountOwner owner7876New = acc7876.Owner;
                AccountOwner owner5678New = acc5678.Owner;

                Assert.NotNull(owner7876New, "У счета с номером 7876 потерялся владелец");
                Assert.NotNull(owner5678New, "У счета с номером 5678 потерялся владелец");

                Assert.AreEqual(owner7876Old.Id, owner5678New.Id
                                , "У счета с номером 5678 владелец поменялся неправильно");
                Assert.AreEqual(owner5678Old.Id, owner7876New.Id
                                , "У счета с номером 7876 владелец поменялся неправильно");
            }
        }
Beispiel #51
0
        protected void Page_Load(object sender, EventArgs e)
        {
            vehiculoCtrl = new VehiculoController();
            homeCtrl     = new HomeController();
            if (!IsPostBack)
            {
                if (!SitePrincipal.IsIntruso())
                {
                    if (SitePrincipal.ExisteActiva())
                    {
                        cargarTipoVehiculo();
                        cargarMarca();

                        string placa = Request.QueryString["placa"];
                        if (!String.IsNullOrEmpty(placa))
                        {
                            txtplaca.Text = placa;
                            var ve = vehiculoCtrl.listar(placa);
                            txtplaca.Text          = ve.NroPlaca;
                            txtpatente.Text        = ve.Patente;
                            txtmotor.Text          = ve.NroMotor;
                            txtmodelo.Text         = ve.Modelo;
                            txtchasis.Text         = ve.NroChasis;
                            txtanio.Text           = Convert.ToString(ve.Año);
                            cbomarca.SelectedValue = ve.CodMarca.ToString();
                            cbotipov.Text          = ve.CodTipoV.ToString();
                        }
                        else
                        {
                            Response.Redirect("~/Vistas/Vehiculos/Index");
                        }
                    }
                    else
                    {
                        SitePrincipal.pagRedireccion = "~/Vistas/Vehiculos/Edit";
                        Response.Redirect("~/Vistas/Empresas/Panel");
                    }
                }
                else
                {
                    Response.Redirect("~/Account/Login");
                }
            }
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            if (exception != null)
            {
                Response.Clear();
                HttpException httpException = exception as HttpException;

                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Home");
                if (httpException == null)
                {
                    routeData.Values.Add("action", "Error");
                    if (exception != null)
                    {
                        Log.Error(exception, "Exception caught in Global.asax1");
                    }
                }
                else
                {
                    switch (httpException.GetHttpCode())
                    {
                    case 404:
                        routeData.Values.Add("action", "PageNotFound");
                        break;

                    case 500:
                        routeData.Values.Add("action", "ServerError");
                        Log.Error(exception, "500 Exception caught in Global.asax");
                        break;

                    default:
                        routeData.Values.Add("action", "Error");
                        Log.Error(exception, "Exception caught in Global.asax (code {Code})", httpException.GetHttpCode());
                        break;
                    }
                }
                Server.ClearError();
                Response.TrySkipIisCustomErrors = true;
                IController errorController = new HomeController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
        }
Beispiel #53
0
        public void TestMethodWithMoq()
        {
            var mockProductRepository = new Mock <IProductRepository>();

            mockProductRepository
            .SetupGet(t => t.Products)
            .Returns(() =>
            {
                return(new Product[] {
                    new Product {
                        Name = "Baseball", Price = 11
                    },
                    new Product {
                        Name = "Football", Price = 8
                    },
                    new Product {
                        Name = "Tennis ball", Price = 13
                    },
                    new Product {
                        Name = "Golf ball", Price = 3
                    },
                    new Product {
                        Name = "Ping pong ball", Price = 12
                    },
                });
            });

            // Arrange
            var controller = new HomeController(mockProductRepository.Object);

            // Act
            var result = controller.Products();

            // Assert
            var products = (Product[])((System.Web.Mvc.ViewResultBase)(result)).Model;

            Assert.AreEqual(5, products.Length, "Length is invalid");

            Assert.IsTrue(products.Where(t => t.Price > 10).Count() >= 3,
                          "Too few > $10");

            Assert.IsTrue(products.Where(t => t.Price < 10).Count() <= 2,
                          "Too many < $10");
        }
Beispiel #54
0
        public void GreenhouseIsActive()
        {
            // Arrange
            string internalTemperature = null;
            double externalTemperature = 20;
            double humidity            = 20;
            double waterLevel          = 20;

            client.setMeasurements(internalTemperature, externalTemperature.ToString(), humidity.ToString(), waterLevel.ToString());
            HomeController controller   = new HomeController();
            string         greenhouseID = client.ID;

            // Act
            controller.getNewestData(greenhouseID);
            Thread.Sleep(2000);

            // Assert
            bool sendingLiveData = client.SendLiveData;

            Assert.IsTrue(sendingLiveData);
            JsonResult data = controller.getNewestData(greenhouseID);

            var type      = data.Data.GetType();
            var pinfo     = type.GetProperty("internalTemperature");
            var readValue = pinfo.GetValue(data.Data, null);

            Assert.IsNull(readValue);

            type      = data.Data.GetType();
            pinfo     = type.GetProperty("externalTemperature");
            readValue = pinfo.GetValue(data.Data, null);
            Assert.AreEqual(externalTemperature, readValue);

            type      = data.Data.GetType();
            pinfo     = type.GetProperty("humidity");
            readValue = pinfo.GetValue(data.Data, null);
            Assert.AreEqual(humidity, readValue);

            type      = data.Data.GetType();
            pinfo     = type.GetProperty("waterlevel");
            readValue = pinfo.GetValue(data.Data, null);
            Assert.AreEqual(waterLevel, readValue);
        }
		public void LoginTestWithException()
		{
			var employee = new Employee
			{
				Username = "",
				Password = ""
			};
			var mockEmployeeDal = new MockEmployeeDal()
			{
				AuthenticateValueToReturn = 1,
				ThrowError = true
			};
			
			var controller = new HomeController(mockEmployeeDal);
			Assert.IsTrue(controller.ModelState.IsValid);
			var result = (ViewResult)controller.Login(employee);
			Assert.IsInstanceOfType(result, typeof(ViewResult));
			Assert.AreEqual("Index", result.ViewName);
		}
        public void ControllerHasCorrectData()
        {
            // Arrange
            var data = new[] { new Product {
                                   Name = "Test", Price = 100M
                               } };
            var _mockRepository = new Mock <IRepository>();

            _mockRepository.Setup(r => r.Products).Returns(data);
            df;
            kjsdf;
            var homeController = new HomeController(_mockRepository.Object);

            // Act
            var viewResult = homeController.Index();

            // Assert
            Assert.Equal(data, viewResult.ViewData.Model);
        }
Beispiel #57
0
        public void VerifyInValidId()
        {
            //Arrange
            var repository = new Mock <IProductRepository>();

            repository.Setup(x => x.GetProductById(It.IsInRange <int>(1, 3, Range.Inclusive))).Returns(new Product {
                Id = 1, Name = "Product 1"
            });

            var controller = new HomeController(repository.Object);

            //Act
            var result = Assert.IsType <ViewResult>(controller.Details(6));


            // Assert

            Assert.Null(result.Model);
        }
        public void AddCommentTest()
        {
            // Arrange
            var    repo           = new FakeStoriesRepository();
            var    homeController = new HomeController(repo);
            string com            = "Great story.";
            string title          = "King of Grapes";

            repo.AddInitialStories();
            Story   tstory = repo.Retrieve(title);
            Comment tcom   = new Comment();

            tcom.Text = com;
            // Act
            homeController.Comment(com, title);
            // Assert
            Assert.Equal(1, repo.Retrieve(title).Subjects.Count);
            Assert.Equal(tcom.Text, tstory.Subjects[0].Text);
        }
        public void RegisterTest()
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                UserRegisterModel model      = new UserRegisterModel();
                HomeController    controller = new HomeController();
                model.Age = 21;
                model.Autonomous_community = "Andalucía";
                model.Email           = "*****@*****.**";
                model.Genre           = "Masculino";
                model.Username        = "******";
                model.Password        = "******";
                model.ConfirmPassword = "******";

                ActionResult ar = controller.Register(model);

                Assert.IsNotNull(ar);
            }
        }
        public void Can_Send_Pagination_View_Model()
        {
            // Arrange
            Mock <IStoreRepository> mock = new Mock <IStoreRepository>();

            mock.Setup(m => m.Products).Returns((new Product[]
            {
                new Product {
                    ProductID = 1, Name = "P1"
                },
                new Product {
                    ProductID = 2, Name = "P2"
                },
                new Product {
                    ProductID = 3, Name = "P3"
                },
                new Product {
                    ProductID = 4, Name = "P4"
                },
                new Product {
                    ProductID = 5, Name = "P5"
                }
            }).AsQueryable <Product>());

            // Arrange
            HomeController controller =
                new HomeController(mock.Object)
            {
                PageSize = 3
            };

            // Act
            ProductsListViewModel result =
                controller.Index(null, 2).ViewData.Model as ProductsListViewModel;

            // Assert
            PagingInfo pageInfo = result.PagingInfo;

            Assert.Equal(2, pageInfo.CurrentPage);
            Assert.Equal(3, pageInfo.ItemsPerPage);
            Assert.Equal(5, pageInfo.TotalItems);
            Assert.Equal(2, pageInfo.TotalPages);
        }