コード例 #1
0
ファイル: UnitTest1.cs プロジェクト: MaxiAdad31/ChallengeMS
        public void GetSuccess()
        {
            var result = _postController.Get();

            Assert.NotNull(result);
            Assert.NotEmpty(result);
        }
コード例 #2
0
        public void T3_SecoesAninhadas()
        {
            var            ownerName   = "Teste3 VariasPostagens";
            var            login       = $"emanuel3_{DateTime.Now.ToString("hhMMss")}";
            var            password    = "******";
            var            description = "T3 Blog teste para validação do projeto";
            BlogController blogCtr     = new BlogController();
            var            idBlog      = blogCtr.Post(
                new BlogModel
            {
                OwnerName   = ownerName,
                Login       = login,
                Password    = password,
                Description = description
            });

            PostController postCtr = new PostController();

            var postagem = new PostModel
            {
                IdBlog   = idBlog,
                Datahora = DateTime.Now,
                Titulo   = $"T3_Post[{DateTime.Now.ToLongTimeString()}]"
            };

            // 4 filhas com 3 netas em cada uma
            for (int i = 0; i < 4; i++)
            {
                postagem.addSecao(new SecaoModel
                {
                    SubTitulo = $"T3_SecaoFilha[{i}]",
                    Conteudo  = "Teste3 com algum texto qualquer"
                });

                for (int j = 0; j < 3; j++)
                {
                    postagem.Secoes[i].addSecao(new SecaoModel
                    {
                        SubTitulo = $"T3_SecaoNeta[{i},{j}]",
                        Conteudo  = "Teste3 com algum texto qualquer"
                    });
                }
            }

            var idPost = postCtr.Post(idBlog, postagem);

            // V A L I D A Ç Ã O ///////////////////////

            // várias leituras diferentes
            var secao_0_1 = postCtr.Get(idBlog, idPost).Secoes[0].Secoes[1];
            var secao_2_2 = postCtr.Get(idBlog, idPost).Secoes[2].Secoes[2];
            var secao_3_0 = postCtr.Get(idBlog, idPost).Secoes[3].Secoes[0];

            // Conferindo os títulos gerados
            Assert.IsNotNull(secao_0_1);
            Assert.AreEqual("T3_SecaoNeta[0,1]", secao_0_1.SubTitulo);
            Assert.AreEqual("T3_SecaoNeta[2,2]", secao_2_2.SubTitulo);
            Assert.AreEqual("T3_SecaoNeta[3,0]", secao_3_0.SubTitulo);
        }
コード例 #3
0
        public async void DeletePostTest()
        {
            PostController postController = new PostController(new PostRepository(_dataContext));

            var postToDelete = (Post)((OkObjectResult)await postController.Get("test title updated")).Value;
            await postController.Delete(postToDelete.Id);

            var postDeleted = (Post)((OkObjectResult)await postController.Get("test title updated")).Value;

            Assert.Null(postDeleted);
        }
コード例 #4
0
        public async void UpdatePostTest()
        {
            PostController postController = new PostController(new PostRepository(_dataContext));

            var postToUpdate = (Post)((OkObjectResult)await postController.Get(post.Title)).Value;

            postToUpdate.Title = "test title updated";
            await postController.Put(postToUpdate);

            var postUpdated = (Post)((OkObjectResult)await postController.Get(postToUpdate.Title)).Value;

            Assert.NotNull(postUpdated);
        }
コード例 #5
0
        public LoginData GetAdvancedPostWithoutSessionkey()
        {
            // Arrange
            LoginData loginData = CreatePost();

            PostController        postController        = new PostController();
            CommentController     commentController     = new CommentController();
            VoteCommentController voteCommentController = new VoteCommentController();

            commentController.Post(loginData.sessionkey, Mocks.comment1);
            commentController.Post(loginData.sessionkey, Mocks.comment2);
            commentController.Post(loginData.sessionkey, Mocks.subComment);
            voteCommentController.Post(loginData.sessionkey, Mocks.voteOnCommentPositive);
            voteCommentController.Post(loginData.sessionkey, Mocks.voteOnCommentNegative2);
            postController.Get(loginData.sessionkey, 1);

            // Act
            var actionResult = postController.Get(null, 1).Result;
            var actual       = (actionResult as OkObjectResult).Value as ComplexAnswer;
            var data         = actual.data as Post;

            // Assert
            Assert.IsType <OkObjectResult>(actionResult);
            Assert.Equal(TestSetup.NormalAnswer.code, actual.code);
            Assert.Equal(TestSetup.NormalAnswer.message, actual.message);
            Assert.Equal(TestSetup.NormalAnswer.success, actual.success);

            Assert.Equal(Mocks.post.title, data.title);
            Assert.Equal(Mocks.post.description, data.description);
            Assert.Equal(Mocks.post.path, data.path);

            Assert.Equal(Mocks.comment1.text, data.comment[0].text);
            Assert.Equal(1, data.comment[0].upvotes);
            Assert.Equal(0, data.comment[0].downvotes);
            Assert.Equal(0, data.comment[0].yourvote);

            Assert.Equal(Mocks.comment2.text, data.comment[1].text);
            Assert.Equal(0, data.comment[1].upvotes);
            Assert.Equal(1, data.comment[1].downvotes);
            Assert.Equal(0, data.comment[1].yourvote);

            Assert.Equal(Mocks.subComment.text, data.comment[0].comment[0].text);
            Assert.Equal(0, data.comment[0].comment[0].downvotes);
            Assert.Equal(0, data.comment[0].comment[0].upvotes);
            Assert.Equal(0, data.comment[0].comment[0].yourvote);

            return(loginData);
        }
コード例 #6
0
        public async Task PostAUser()
        {
            var fileMock = new Mock <IFormFile>();
            //Setup mock file using a memory stream
            var content  = "Hello World from a Fake File";
            var fileName = "test.mp4";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);
            var postMockOject = new Mock <IPost>();

            postMockOject.Setup(r => r.Get("jhgfdsfghjkljhgf")).ReturnsAsync(GetApost);
            var mailSeviceObject    = new Mock <IMailService>();
            var loggerObject        = new Mock <ILogger <PostController> >();
            var userObject          = new Mock <IUser>();
            var photoUploadObject   = new Mock <IPhoto>();
            var youTubeObject       = new Mock <IYoutube>();
            var videoObject         = new Mock <IVideo>();
            var mapper              = new Mock <IMapper>();
            var redisObject         = new Mock <IRedis>();
            var photoAccessorObject = new Mock <IPhotoAccessor>();
            var postController      = new PostController(postMockOject.Object, mailSeviceObject.Object, loggerObject.Object, userObject.Object, photoUploadObject.Object, youTubeObject.Object, mapper.Object, photoAccessorObject.Object, videoObject.Object, redisObject.Object);
            var result              = await postController.Get(It.IsAny <GetPostModel>());

            Assert.IsType <ObjectResult>(result);
        }
コード例 #7
0
        public void GetPosts()
        {
            // Arrange
            var mockRepo = new Mock <IPostService>();

            mockRepo.Setup(x => x.Search("State == \"Activo\"", null, "Client")).Returns(GetMockPosts().Where(x => x.State == Constants.Strings.States.Active));
            var configuration = new MapperConfiguration(cfg => cfg.AddProfile(new PostProfile()));
            var mapper        = new Mapper(configuration);



            var controller = new PostController(mockRepo.Object, mapper);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = createContext()
                }
            };

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

            // Assert
            var viewResult = Assert.IsType <OkObjectResult>(result);
            var model      = Assert.IsAssignableFrom <IEnumerable <PostDto> >(
                viewResult.Value);

            Assert.Single(model);
        }
コード例 #8
0
        public void GetPostsAuth()
        {
            // Arrange
            var mockRepo = new Mock <IPostService>();

            mockRepo.Setup(x => x.Search("State == \"Activo\" OR ((State == \"Draft\" OR State == \"Privado\" )AND  ClientId == \"3a7fc558-6db4-4835-956c-521e2ba0a234\")", null, "Client")).Returns(GetMockPosts());
            var configuration = new MapperConfiguration(cfg => cfg.AddProfile(new PostProfile()));
            var mapper        = new Mapper(configuration);



            var controller = new PostController(mockRepo.Object, mapper);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = Auth()
                }
            };

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

            // Assert
            var viewResult = Assert.IsType <OkObjectResult>(result);
            var model      = Assert.IsAssignableFrom <IEnumerable <PostDto> >(
                viewResult.Value);

            Assert.Equal(5, model.Count());
        }
コード例 #9
0
        public void GetAll()
        {
            var postController = new PostController(GetMockService());
            var result         = postController.Get().Result.Value;

            Assert.IsInstanceOfType(result, typeof(List <Post>));
        }
コード例 #10
0
        public async Task Get_WithPageReturnsPaged_Succeeds()
        {
            // setup
            _loggerMock = new Mock <ILoggerFactory>();
            _applicationUnitOfWorkMock = new Mock <IApplicationUnitOfWork>();
            var posts = GetTestPosts(6);

            _postRepositoryMock = new Mock <IPostRepository>();
            _postRepositoryMock.Setup(x => x.GetAllWithCategory()).Returns(Task.FromResult(posts));
            _applicationOptionsMock = new Mock <IOptions <ApplicationOptions> >();
            _applicationOptionsMock.Setup(x => x.Value).Returns(new ApplicationOptions {
                PageSize = 5
            });
            _applicationUnitOfWorkMock.Setup(x => x.Posts).Returns(_postRepositoryMock.Object);
            _sut = new PostController(_applicationUnitOfWorkMock.Object, _applicationOptionsMock.Object, Mapper.Instance, _loggerMock.Object);

            // action
            var result = await _sut.Get(null, false, null, 2) as JsonResult;

            var jsonResult = (IEnumerable <PostModel>)result.Value;

            // assert
            Assert.NotNull(jsonResult);
            Assert.Equal(1, jsonResult.Count());
            Assert.Equal("post 5", jsonResult.First().Title);
        }
コード例 #11
0
        public async Task Get_WithIdReturnsPost_Succeeds()
        {
            // setup
            _loggerMock = new Mock <ILoggerFactory>();
            _applicationUnitOfWorkMock = new Mock <IApplicationUnitOfWork>();
            var posts = GetTestPosts(5);
            IEnumerable <Post> post = new List <Post> {
                posts.Last()
            };

            _postRepositoryMock = new Mock <IPostRepository>();
            _postRepositoryMock.Setup(x => x.GetWithCategory(It.IsAny <Expression <Func <Post, bool> > >())).Returns(Task.FromResult(post));
            _applicationOptionsMock = new Mock <IOptions <ApplicationOptions> >();
            _applicationOptionsMock.Setup(x => x.Value).Returns(new ApplicationOptions {
                PageSize = 5
            });
            _applicationUnitOfWorkMock.Setup(x => x.Posts).Returns(_postRepositoryMock.Object);
            _sut = new PostController(_applicationUnitOfWorkMock.Object, _applicationOptionsMock.Object, Mapper.Instance, _loggerMock.Object);

            // action
            var result = await _sut.Get(post.First().Id) as JsonResult;

            var jsonResult = (PostModel)result.Value;

            // assert
            Assert.NotNull(jsonResult);
            Assert.Equal(post.First().Id, jsonResult.Id);
        }
コード例 #12
0
        public void GetByIdNotFound()
        {
            var postId         = 15;
            var postController = new PostController(GetMockService());
            var result         = postController.Get(postId).Result;

            Assert.IsInstanceOfType(result.Result, typeof(NotFoundResult));
        }
コード例 #13
0
        public void DeletePost()
        {
            // Arrange
            LoginData loginData = CreatePost();

            PostController postController = new PostController();

            var getPostResult = postController.Get(loginData.sessionkey, 1).Result;
            var createdPost   = ((getPostResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            // Act
            postController.Delete(loginData.sessionkey, createdPost.postId);

            // Assert
            var getPostNotFoundResult = postController.Get(loginData.sessionkey, 1).Result;

            Assert.IsType <NotFoundObjectResult>(getPostNotFoundResult);
        }
コード例 #14
0
        public void GetPostById_OK_Response()
        {
            var p = Builder <Post> .CreateNew().Build();

            _mockService.Setup(x => x.GetById(1)).Returns(p);

            var getResult = _controller.Get(1);
            var result    = getResult as OkObjectResult;
            var content   = result.Value as Post;

            Assert.Equal((int)HttpStatusCode.OK, result.StatusCode);
            Assert.NotNull(content);
            Assert.Equal(p.Id, content.Id);
            Assert.Equal(p.Title, content.Title);
            Assert.Equal(p.Summary, content.Summary);
            Assert.Equal(p.Text, content.Text);
            _mockService.Verify(x => x.GetById(1), Times.Once);
        }
コード例 #15
0
        public async void CreatePostTest()
        {
            PostController postController = new PostController(new PostRepository(_dataContext));

            await postController.Post(post);

            var result = await postController.Get(post.Title);

            Assert.NotNull(result);
        }
コード例 #16
0
        public Post TestGetByTModel()
        {
            var name = TestAdd();
            PostController pc = new PostController();

            var existing = pc.Get(new Post() { Name = name });
            Assert.IsNotNull(existing);

            return existing;
        }
コード例 #17
0
        public async Task Get()
        {
            _fixture.AddSampleData();

            var  controller = new PostController(_fixture.GetService <IPostService>());
            Post post       = (await controller.Get(_fixture.SampleGuid) as JsonResult).Value as Post;

            Assert.NotNull(post);
            Assert.Equal(_fixture.SampleGuid, post.Id);
        }
コード例 #18
0
        public void GetEntitysExist()
        {
            // Arrange
            var controller = new PostController(GetMockRepo());

            // Act
            var result = controller.Get(1, 1);

            // Assert
            Assert.IsType <OkObjectResult>(result);
        }
コード例 #19
0
        public void GetEntitysBadRepository()
        {
            // Arrange
            var controller = new PostController(GetMockRepo(false));

            // Act
            var result = controller.Get(1, 1);

            // Assert
            Assert.IsType <UnprocessableEntityObjectResult>(result);
        }
コード例 #20
0
        public async Task GetAll()
        {
            _fixture.AddSampleData();

            using (var context = _fixture.CreateContext()) {
                var controller = new PostController(_fixture.GetService <IPostService>());
                var posts      = await controller.Get();

                Assert.True(posts.Count() == _fixture.SampleCount);
            }
        }
コード例 #21
0
        public void GetEntitysNoExist()
        {
            // Arrange
            var controller = new PostController(GetMockRepo());

            // Act
            var result = controller.Get(0, 0);

            // Assert
            Assert.IsType <NoContentResult>(result);
        }
コード例 #22
0
        public void GetById()
        {
            var postMock       = mockData.FirstOrDefault(p => p.Id == 3);
            var postController = new PostController(GetMockService());
            var result         = postController.Get(postMock.Id).Result.Value;

            Assert.IsNotNull(result);
            Assert.AreEqual(postMock.Id, result.Id);
            Assert.AreEqual(postMock.Autor, result.Autor);
            Assert.AreEqual(postMock.Title, result.Title);
            Assert.AreEqual(postMock.Body, result.Body);
        }
コード例 #23
0
        public void GetEntityNoExist()
        {
            // Arrange
            var  controller = new PostController(GetMockRepo());
            uint id         = 0;

            // Act
            var result = controller.Get(id);

            // Assert
            Assert.IsType <NotFoundObjectResult>(result);
        }
コード例 #24
0
        public void GetDetails()
        {
            var postId          = 1;
            var postManagerMock = new Mock <IPostManager>();

            postManagerMock.Setup(pm => pm.Get(It.IsAny <int>())).Returns(new PostDetailsModel());

            var controller = new PostController(postManagerMock.Object);
            var result     = controller.Get(postId);

            postManagerMock.Verify(p => p.Get(postId), Times.Once);
            result.Should().NotBeNull();
        }
コード例 #25
0
        public void TestUpdate()
        {
            var existing = TestGetByTModel();
            existing.Title = "Updated title";

            var pc = new PostController();
            pc.Update(existing);

            var updated = pc.Get(existing.Name);

            Assert.AreEqual(existing.Title, updated.Title);

        }
コード例 #26
0
        public void UpvoteAndDownvoteSamePost()
        {
            // Arrange
            LoginData loginData = CreatePost();

            PostController postController = new PostController();
            var            getPostResult  = postController.Get(loginData.sessionkey, 1).Result;
            var            createdPost    = ((getPostResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            VoteController voteController = new VoteController();

            // Act
            voteController.Post(loginData.sessionkey, Mocks.downvote);
            voteController.Post(loginData.sessionkey, Mocks.upvote);

            // Assert
            var actionResult = postController.Get(loginData.sessionkey, 1).Result;
            var actual       = ((actionResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            Assert.Equal(Mocks.createPosts[0].title, actual.title);
            Assert.Equal(Mocks.createPosts[0].description, actual.description);
            Assert.Equal(Mocks.createPosts[0].path, actual.path);
            Assert.Equal(1, actual.upvotes);
        }
コード例 #27
0
        public void GetList()
        {
            var postManagerMock = new Mock <IPostManager>();

            postManagerMock.Setup(pm => pm.List()).Returns(
                new List <PostListItemModel>
            {
                new PostListItemModel()
            });

            var controller = new PostController(postManagerMock.Object);
            var result     = controller.Get();

            postManagerMock.Verify(p => p.List(), Times.Once);
            result.Count().Should().Be(1);
        }
コード例 #28
0
        public async void Get_Not_Exists()
        {
            PostControllerMockFacade mock = new PostControllerMockFacade();

            mock.ServiceMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult <ApiPostResponseModel>(null));
            PostController controller = new PostController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            IActionResult response = await controller.Get(default(int));

            response.Should().BeOfType <StatusCodeResult>();
            (response as StatusCodeResult).StatusCode.Should().Be((int)HttpStatusCode.NotFound);
            mock.ServiceMock.Verify(x => x.Get(It.IsAny <int>()));
        }
コード例 #29
0
        public void Get_ReturnsAViewResult_WithAListOfPosts()
        {
            //Arrage
            var mockService = new Mock <IDataService>();

            mockService.Setup(x => x.GetPostDetail(It.IsAny <int>())).Returns(new PostExtended
            {
                PostId   = 1,
                Title    = "Testing Post Controller using Moq",
                Score    = 60,
                PostBody = "First time using Unit Test with Moq to test the controller!",
                Answers  = new List <string> {
                    "Well, hope this works...", "Ohlala it works"
                },
                UserName = "******"
            });
            var mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelper.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <object>()))
            //Using Func + Reflection, because the id was created as an Anonymous Type in ModelFactory.
            .Returns((string urlString, object idObject) =>
            {
                Type typeOfIdObject = idObject.GetType();
                int valueOfIdObject =
                    (int)typeOfIdObject.GetProperty("id").GetValue(idObject, null);
                return("http://localhost/api/posts/" + valueOfIdObject);
            });

            var controller = new PostController(mockService.Object);

            controller.Url = mockUrlHelper.Object;

            //Action
            IActionResult   actionResult      = controller.Get(1);
            OkObjectResult  okObjectResult    = actionResult as OkObjectResult;
            PostDetailModel asPostDetailModel = (PostDetailModel)okObjectResult.Value;

            //Assert
            Assert.Equal("http://localhost/api/posts/1", asPostDetailModel.Url);
            Assert.Equal("Testing Post Controller using Moq", asPostDetailModel.Title);
            Assert.Equal(60, asPostDetailModel.Score);
            Assert.Equal("First time using Unit Test with Moq to test the controller!", asPostDetailModel.PostBody);
            Assert.Equal("Well, hope this works...", asPostDetailModel.Answers[0]);
            Assert.Equal("Ohlala it works", asPostDetailModel.Answers[1]);
            Assert.Equal("Group 7 RAWDATA", asPostDetailModel.UserName);
        }
コード例 #30
0
        public void GetPosts_ReturnsOk()
        {
            var dataServiceMock = new Mock <IDataService>();

            dataServiceMock
            .Setup(o => o.GetPostRepository())
            .Returns(new DataAccessLayer.Repository.GenericReadableRepository <Post>(new DatabaseContext()));
            var urlHelperMock = new Mock <IUrlHelper>();

            var ctrl = new PostController(dataServiceMock.Object);

            ctrl.Url = urlHelperMock.Object;

            var response = ctrl.Get();

            Assert.IsType <OkObjectResult>(response);
        }
コード例 #31
0
        public void GetPost()
        {
            // Arrange
            LoginData loginData = CreatePost();

            PostController postController = new PostController();

            // Act
            var actionResult = postController.Get(loginData.sessionkey, 1).Result;
            var actual       = ((actionResult as OkObjectResult).Value as ComplexAnswer).data as Post;

            // Assert
            Assert.IsType <OkObjectResult>(actionResult);
            Assert.Equal(Mocks.createPosts[0].title, actual.title);
            Assert.Equal(Mocks.createPosts[0].description, actual.description);
            Assert.Equal(Mocks.createPosts[0].path, actual.path);
            Assert.Equal(1, actual.userId);
            Assert.Equal("testusername", actual.user);
        }
コード例 #32
0
        public void GetEntitysByAuthor()
        {
            // Arrange
            var controller = new PostController(GetMockRepo());

            // Act
            var result = controller.Get(author: 1) as OkObjectResult;
            var list   = result.Value as IEnumerable;
            var amount = 0;

            foreach (var item in list)
            {
                amount++;
            }

            // Assert
            Assert.IsType <OkObjectResult>(result);
            Assert.True(amount == 1);
        }