public void Execute_ShouldCallAddStudentMethodWithCorrectParametersExactlyOnce_WhenValidArgumentsArePassed( string firstName, string lastName, string grade) { //Arrange var parameters = new List <string>() { firstName, lastName, grade }; var mockedStudent = new Mock <IStudent>(); var mockedFactory = new Mock <IStudentFactory>(); mockedFactory.Setup(f => f.CreateStudent("Pesho", "Peshov", Grade.Second)) .Returns(mockedStudent.Object); var mockedEngine = new Mock <ISchoolSystemEngine>(); var mockStudentRepo = new Mock <IRepository <IStudent> >(); mockedEngine.Setup(e => e.Data.Students).Returns(mockStudentRepo.Object); mockedEngine.Setup(e => e.Data.Students.Add(mockedStudent.Object)); var command = new CreateStudentCommand(mockedFactory.Object); //Act command.Execute(parameters, mockedEngine.Object.Data); //Assert mockedEngine.Verify(e => e.Data.Students.Add(mockedStudent.Object), Times.Once()); }
public async Task <IActionResult> CreateStudent(int classId, [FromBody] CreateStudentCommand command) { command.ClassId = classId; var studentId = await _mediator.Send(command); return(Created($"api/classes/{classId}/students/{studentId}", null)); }
public async Task <StudentResponseModel> PostStudent( [FromForm] StudentRequestModel model, CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); var command = new CreateStudentCommand( model.FirstName, model.LastName, model.MiddleName, model.Email, model.Avatar, model.GroupId ); var studentId = await _mediator.Send(command, cancellationToken); var query = new FindStudentByIdQuery(studentId); var student = await _mediator.Send(query, cancellationToken); var response = _mapper.Map <StudentResponseModel>(student); return(response); }
public void SuccesfullyRemoveStudent() { // Arrange string firstName = "pesho"; string lastName = "peshov"; string grade = "7"; IList <string> args = new List <string>() { firstName, lastName, grade }; var studentFactory = new StudentFactory(); var createStudentCommand = new CreateStudentCommand(studentFactory); var removeStudentCommand = new RemoveStudentCommand(); // Act var createdStudent = createStudentCommand.Execute(args); int studentsBeforeRemove = Engine.Students.Count; removeStudentCommand.Execute(new List <string>() { "0" }); int studentsAfterRemove = Engine.Students.Count; // Assert Assert.AreEqual(studentsBeforeRemove - 1, studentsAfterRemove); }
public void Execute_ShouldIncremnt_IdentityProvider_Value() { var stubStudentFactory = new Mock <IStudentFactory>(); var idProvider = new SchoolSystemIdentityProvider(); var stubSchoolSystemData = new Mock <ISchoolSystemData>(); var mockStudentsCollection = new Mock <ISchoolSystemDataCollection <IStudent> >(); stubSchoolSystemData.SetupGet(ssd => ssd.Students).Returns(mockStudentsCollection.Object); stubSchoolSystemData.SetupGet(ssd => ssd.Teachers).Returns(new Mock <ISchoolSystemDataCollection <ITeacher> >().Object); var commandString = new List <string>() { "Pesho", "Peshev", "11" }; var createStudentCommand = new CreateStudentCommand(stubStudentFactory.Object, idProvider); createStudentCommand.Execute(commandString, stubSchoolSystemData.Object); createStudentCommand.Execute(commandString, stubSchoolSystemData.Object); // Incrementing IdProvider. mockStudentsCollection.Verify(sc => sc.Add(0, It.IsAny <IStudent>()), Times.Once()); mockStudentsCollection.Verify(sc => sc.Add(1, It.IsAny <IStudent>()), Times.Once()); }
public async Task When_InvalidModelPosted_Then_Server_Should_Return_BadRequest( string firstName, string lastName, int studentNumber, int classroomId, string errorMessage) { using var testServer = await CreateWithUserAsync(); var client = testServer.CreateClient(); var command = new CreateStudentCommand( Guid.NewGuid(), firstName, lastName, studentNumber, classroomId, Random.RandomString(200), "Single", null, null); var response = await client.PostAsync(ApiPath, command.ToJsonContent()); await response.Should().BeBadRequestAsync(errorMessage); }
public void CallSchoolSystemDataWithCorrectParameters_WhenPassedArgumentsAreValid() { // arrange var studentFactory = new Mock <IStudentFactory>(); var schoolSystemData = new Mock <ISchoolSystemData>(); IList <string> commandParams = new List <string>() { "Ivan", "Ivanov", "5" }; string firstName = "Ivan"; string lastName = "Ivanov"; Grade grade = Grade.Fifth; var student = new Mock <IStudent>(); student.Setup(x => x.FirstName).Returns(firstName); student.Setup(x => x.LastName).Returns(lastName); student.Setup(x => x.Grade).Returns(grade); studentFactory.Setup(x => x.CreateStudent(firstName, lastName, grade)).Returns(student.Object); var createStudentCommand = new CreateStudentCommand(studentFactory.Object, schoolSystemData.Object); // act createStudentCommand.Execute(commandParams); // assert schoolSystemData.Verify(x => x.AddStudent(0, student.Object), Times.Once); }
public void ReturnCorrectMessage_WhenStudentHasBeenAddedSuccessfully() { // arrange var studentFactory = new Mock <IStudentFactory>(); var schoolSystemData = new Mock <ISchoolSystemData>(); IList <string> commandParams = new List <string>() { "Ivan", "Ivanov", "5" }; string firstName = "Ivan"; string lastName = "Ivanov"; Grade grade = Grade.Fifth; var student = new Mock <IStudent>(); student.Setup(x => x.FirstName).Returns(firstName); student.Setup(x => x.LastName).Returns(lastName); student.Setup(x => x.Grade).Returns(grade); studentFactory.Setup(x => x.CreateStudent(firstName, lastName, grade)).Returns(student.Object); var createStudentCommand = new CreateStudentCommand(studentFactory.Object, schoolSystemData.Object); string expectedMessage = $"A new student with name {firstName} {lastName}, grade {grade} and ID {0} was created."; // act string actualMessage = createStudentCommand.Execute(commandParams); // assert StringAssert.Contains(expectedMessage, actualMessage); }
public void Execute_ShouldReturnCorrectValue_WhenValidArgumentsArePassed() { //Arrange const string expectedResult = "A new student with name Pesho Peshov, grade Second and ID 0 was created."; const string expectedSecondResult = "A new student with name Pesho Peshov, grade Second and ID 0 was created."; var mockedFactory = new Mock <IStudentFactory>(); var mockStudentRepo = new Mock <IRepository <IStudent> >(); var mockedEngine = new Mock <ISchoolSystemEngine>(); mockedEngine.Setup(e => e.Data.Students).Returns(mockStudentRepo.Object); var parameters = new List <string>() { "Pesho", "Peshov", "2" }; var command = new CreateStudentCommand(mockedFactory.Object); //Act var result = command.Execute(parameters, mockedEngine.Object.Data); var secondResult = command.Execute(parameters, mockedEngine.Object.Data); //Assert Assert.AreEqual(expectedResult, result); Assert.AreEqual(expectedSecondResult, secondResult); }
public string CreateStudent(CreateStudentCommand command) { //command.CourseIds = new List<int>() { 4 }; StudentsCommandHandler handler = new StudentsCommandHandler(); return(handler.Handle(command)); }
public void AddTheStudent_WithTheGivenParameters() { // Arrange int currentStudentId = 0; string firstName = "Pesho"; string lastName = "Petrov"; string gradeAsString = "10"; Grade grade = (Grade)int.Parse(gradeAsString); IList <string> parameters = new List <string>() { firstName, lastName, gradeAsString }; var studentFactoryMock = new Mock <IStudentFactory>(); var addStudentMock = new Mock <IAddStudent>(); var studentMock = new Mock <IStudent>(); studentFactoryMock.Setup(sf => sf.CreateStudent(firstName, lastName, grade)).Returns(studentMock.Object); addStudentMock.Setup(s => s.AddStudent(currentStudentId, studentMock.Object)); ICommand createStudentCommand = new CreateStudentCommand(studentFactoryMock.Object, addStudentMock.Object); // Act createStudentCommand.Execute(parameters); // Assert addStudentMock.Verify(s => s.AddStudent(currentStudentId, studentMock.Object), Times.Once()); }
public void ReturnSuccessMessage_WhenTheStudentIsAdded() { // Arrange int currentStudentId = 0; string firstName = "Pesho"; string lastName = "Petrov"; string gradeAsString = "10"; Grade grade = (Grade)int.Parse(gradeAsString); string successMessage = $"A new student with name {firstName} {lastName}, grade {grade} and ID {currentStudentId++} was created."; IList <string> parameters = new List <string>() { firstName, lastName, gradeAsString }; var studentFactoryMock = new Mock <IStudentFactory>(); var addStudentMock = new Mock <IAddStudent>(); var studentMock = new Mock <IStudent>(); studentFactoryMock.Setup(sf => sf.CreateStudent(firstName, lastName, grade)).Returns(studentMock.Object); addStudentMock.Setup(s => s.AddStudent(currentStudentId, studentMock.Object)); ICommand createStudentCommand = new CreateStudentCommand(studentFactoryMock.Object, addStudentMock.Object); // Act string executionResult = createStudentCommand.Execute(parameters); // Assert StringAssert.Contains(successMessage, executionResult); }
public async Task <IActionResult> Create(StudentDto studentDto) { var createStudentCommand = new CreateStudentCommand(studentDto); var response = await _mediator.Send(createStudentCommand); return(Ok(response)); }
public Task <CommandExecutionResult <Student> > Handle(CreateStudentCommand request) { try { var student = new Student(request.FirstName, request.LastName, request.BirthDate, request.Gpi); _context.Set <Student>().Add(student); _context.SaveChangesAsync(); return(Task.FromResult(new CommandExecutionResult <Student>() { Success = true, Data = student })); } catch (Exception exception) { return(Task.FromResult(new CommandExecutionResult <Student>() { Success = false, Exception = exception })); } }
public void TestExecute_PassValidParameters_ShouldCallServiceAddStudentCorrectly() { var parameters = new string[] { "Pesho", " Peshev", "11" }; var mockedStudent = new Mock <IStudent>(); mockedStudent.Setup(t => t.FirstName).Returns(parameters[0]); mockedStudent.Setup(t => t.LastName).Returns(parameters[1]); mockedStudent.Setup(x => x.Grade).Returns((Grade)int.Parse(parameters[2])); var mockedFactory = new Mock <IStudentFactory>(); mockedFactory.Setup(x => x.CreateStudent(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Grade>())) .Returns(mockedStudent.Object); var mockedService = new Mock <ISchoolService>(); mockedService.Setup(s => s.AddStudent(It.IsAny <IStudent>())).Returns(1); var command = new CreateStudentCommand(mockedFactory.Object, mockedService.Object); command.Execute(parameters); mockedService.Verify(x => x.AddStudent(mockedStudent.Object), Times.Once); }
public void CreateNewUser(string name, string email, string courseID, string courseName ) { var newStudentCourseList = (new string[] { courseID }).ToList(); CreateStudentCommand command = new CreateStudentCommand(name, email, newStudentCourseList, loginService.CurrentUser); command.SuccessActions.Add( ( args ) => HandleUserResult( args, courseName) ); command.Execute(); }
public ActionResult Create() { ExecutorServiceClient client = new ExecutorServiceClient(); var courses = client.ReadCourses(new CourseListQuery()); var student = new CreateStudentCommand(); return(View(student)); }
public async Task Should_update_grade() { // create course var createCourseCommand = new CreateCourseCommand() { Id = Guid.NewGuid(), Code = 1, Name = "Course 1", Description = "Test" }; var createCourseCommandHandler = new CreateCourseCommandHandler(this.autoMapper, this.context); var courseResult = await createCourseCommandHandler.Handle(createCourseCommand, CancellationToken.None); // Create student var createStudentCommand = new CreateStudentCommand() { Id = Guid.NewGuid(), FirstName = "Milos", LastName = "Stojkovic", Address = "Bata Noleta 31", City = "Sokobanja", DateOfBirth = new DateTime(1991, 3, 18), State = "Srbija", Gender = 0 }; var createStudentCommandHandler = new CreateStudentCommandHandler(this.autoMapper, this.context); var studentResult = await createStudentCommandHandler.Handle(createStudentCommand, CancellationToken.None); var createOrUpdateEnrollmentCommand = new CreateOrUpdateEnrollmentCommand() { Id = createStudentCommand.Id, CourseCode = createCourseCommand.Code, Grade = (int)Domain.Enumerations.Grade.Seven }; var createOrUpdateEnrollmentCommandHandler = new CreateOrUpdateEnrollmentCommandHandler(this.context); var result = await createOrUpdateEnrollmentCommandHandler.Handle(createOrUpdateEnrollmentCommand, CancellationToken.None); result.ShouldBe(true); var enrollment = await this.context.Enrollment .FirstOrDefaultAsync(e => e.Course.Code == createOrUpdateEnrollmentCommand.CourseCode && e.Student.Id == createOrUpdateEnrollmentCommand.Id, CancellationToken.None); enrollment.Grade.ShouldBe(Domain.Enumerations.Grade.Seven); createOrUpdateEnrollmentCommand.Grade = (int)Domain.Enumerations.Grade.Eight; var updateResult = await createOrUpdateEnrollmentCommandHandler.Handle(createOrUpdateEnrollmentCommand, CancellationToken.None); updateResult.ShouldBe(true); var updatedEnrollment = await this.context.Enrollment .FirstOrDefaultAsync(e => e.Course.Code == createOrUpdateEnrollmentCommand.CourseCode && e.Student.Id == createOrUpdateEnrollmentCommand.Id, CancellationToken.None); updatedEnrollment.Grade.ShouldBe(Domain.Enumerations.Grade.Eight); }
public void NotToThrow_IfPassedParametersAreValid() { var mockedEngine = new Mock <IEngine>(); var mockedPersonFactory = new Mock <IPersonFactory>(); var command = new CreateStudentCommand(mockedEngine.Object, mockedPersonFactory.Object); Assert.AreEqual(typeof(CreateStudentCommand), command.GetType()); }
public void ConstructorWithParametersShouldSetCorrect() { Mock <ISchoolSystemFactory> mockedSchoolSystemFactory = new Mock <ISchoolSystemFactory>(); Mock <ISchoolRegister> mockedSchoolRegister = new Mock <ISchoolRegister>(); CreateStudentCommand createStudentCommand = new CreateStudentCommand(mockedSchoolSystemFactory.Object, mockedSchoolRegister.Object); Assert.IsInstanceOf <CreateStudentCommand>(createStudentCommand); }
public async Task Should_throw_delete_failure_exception() { // create course var createCourseCommand = new CreateCourseCommand() { Id = Guid.NewGuid(), Code = 1, Name = "Course 1", Description = "Test" }; var createCourseCommandHandler = new CreateCourseCommandHandler(this.autoMapper, this.context); var commandResult = await createCourseCommandHandler.Handle(createCourseCommand, CancellationToken.None); commandResult.ShouldBe(true); // Create student var createStudentCommand = new CreateStudentCommand() { Id = Guid.NewGuid(), FirstName = "Milos", LastName = "Stojkovic", Address = "Bata Noleta 31", City = "Sokobanja", DateOfBirth = new DateTime(1991, 3, 18), State = "Srbija", Gender = 0 }; var createStudentCommandHandler = new CreateStudentCommandHandler(this.autoMapper, this.context); commandResult = await createStudentCommandHandler.Handle(createStudentCommand, CancellationToken.None); commandResult.ShouldBe(true); var createOrUpdateEnrollmentCommand = new CreateOrUpdateEnrollmentCommand() { Id = createStudentCommand.Id, CourseCode = createCourseCommand.Code, Grade = (int)Domain.Enumerations.Grade.Seven }; var createOrUpdateEnrollmentCommandHandler = new CreateOrUpdateEnrollmentCommandHandler(this.context); commandResult = await createOrUpdateEnrollmentCommandHandler.Handle(createOrUpdateEnrollmentCommand, CancellationToken.None); commandResult.ShouldBe(true); var deleteStudentCommand = new DeleteStudentCommand() { Id = createStudentCommand.Id }; var deleteStudentCommandHandler = new DeleteStudentCommandHandler(this.context); await Assert.ThrowsAsync <DeleteFailureException>(() => deleteStudentCommandHandler.Handle(deleteStudentCommand, CancellationToken.None)); }
public async Task <IActionResult> Add([FromBody] CreateStudentCommand addNew) { if (addNew == null) { return(BadRequest()); } var result = await _createStudentCommand.Handle(addNew, CancellationToken.None); return(CreatedAtAction(nameof(Add), addNew, result)); }
public async Task <IHttpActionResult> CreateStudent() { var command = new CreateStudentCommand { FirstName = "Check", LastName = "This" }; await _createStudent.Handle(command); // retunr the new student id from the command return(Ok(command.Id)); }
public RedirectToRouteResult DoCreate(StudentDTO model) { var cmd = new CreateStudentCommand(Guid.NewGuid(), model.FirstName, model.LastName); commandBus.Send(cmd); return(RedirectToRoute(new { controller = "Student", action = "Index" })); }
// This method is also an example of a webapi which doesn't want to expose the domain model. So students are created with a specific view model, // and so we need to perform fluent validation on that view model. It may seem redundant to validate this model, then our service validates the command as well (which is the same in this case). // But depending on your implementation, your service might allow more configurations, or it could be an "CreateOrUpdate" service, and so you would want to do some preliminary validation // here before calling the service. So really I'm just trying to show all potential ways to use these features. Your project architecture, complexity and code style/conventions might // favor one more than the other, but the building blocks are here. public async Task <int> Post([FromBody] CreateOrUpdateStudentViewModel model) { var command = new CreateStudentCommand { FirstMidName = model.FirstMidName, LastName = model.LastName, EnrollmentDate = model.EnrollmentDate }; var student = await _mediator.SendAsync(command); return(student.Id); }
public void AddMarkOnlyToSpecifiedStudent() { // Arrange string studentFirstName1 = "pesho"; string studentLastName1 = "peshov"; string studentFirstName2 = "gosho"; string studentLastName2 = "goshev"; string grade = "7"; string teacherFirstName = "ivan"; string teacherLastName = "ivanov"; string subject = "1"; string mark = "2"; IList <string> studentArgs1 = new List <string>() { studentFirstName1, studentLastName1, grade }; IList <string> studentArgs2 = new List <string>() { studentFirstName2, studentLastName2, grade }; IList <string> teacherArgs = new List <string>() { teacherFirstName, teacherLastName, subject }; var studentFactory = new StudentFactory(); var createStudentCommand = new CreateStudentCommand(studentFactory); var teacherFactory = new TeacherFactory(); var createTeacherCommand = new CreateTeacherCommand(teacherFactory); var teacherAddMarkCommand = new TeacherAddMarkCommand(); // Act createStudentCommand.Execute(studentArgs1); createStudentCommand.Execute(studentArgs2); createTeacherCommand.Execute(teacherArgs); var addMarkMessage = teacherAddMarkCommand.Execute(new List <string>() { "0", "0", mark }); // Assert Assert.IsTrue(Engine.Students[0].Marks.Count == 1); Assert.IsTrue(Engine.Students[1].Marks.Count == 0); }
public void CreateStudentWithCorrectParametersByFactory_WhenParametersAreCorrect(IList <string> parameters) { // Arrange var parametersTuple = GetParameters(parameters); var mockStudentFactory = new Mock <IStudentFactory>(); var mockAddStudent = new Mock <IAddStudent>(); var createStudentCommand = new CreateStudentCommand(mockStudentFactory.Object, mockAddStudent.Object); // Act createStudentCommand.Execute(parameters); // Assert mockStudentFactory.Verify(a => a.CreateStudent(parametersTuple.Item1, parametersTuple.Item2, parametersTuple.Item3), Times.Once()); }
public ActionResult Create(CreateStudentCommand command) { try { ExecutorServiceClient client = new ExecutorServiceClient(); client.CreateStudent(command); return(RedirectToAction("List")); } catch { return(View()); } }
public async Task ShouldBeAbleToCreateStudents() { var createStudentCommand = new CreateStudentCommand { FirstName = "satish", LastName = "Venkatakrishnan", EnrollmentDate = DateTime.Now }; var id = await SendAsync(createStudentCommand); StudentEntity studentEntity = FindAsync <StudentEntity>(id); studentEntity.FirstName.Should().Be("satish"); }
public async Task Should_return_sutdents_with_passed_coruces() { // create course var courseQuery = new CreateCourseCommand() { Id = Guid.NewGuid(), Code = 5, Name = "Course 2", Description = "Test" }; var courseHandler = new CreateCourseCommandHandler(this.autoMapper, this.context); var courseResult = await courseHandler.Handle(courseQuery, CancellationToken.None); // Create student var createStudentCommand = new CreateStudentCommand() { Id = Guid.NewGuid(), FirstName = "Milos", LastName = "Stojkovic", Address = "Bata Noleta 31", City = "Sokobanja", DateOfBirth = new DateTime(1991, 3, 18), State = "Srbija", Gender = 0 }; var createStudentCommandHandler = new CreateStudentCommandHandler(this.autoMapper, this.context); var studentResult = await createStudentCommandHandler.Handle(createStudentCommand, CancellationToken.None); var createOrUpdateEnrollmentCommand = new CreateOrUpdateEnrollmentCommand() { Id = createStudentCommand.Id, CourseCode = courseQuery.Code, Grade = (int)Domain.Enumerations.Grade.Seven }; var createOrUpdateEnrollmentCommandHandler = new CreateOrUpdateEnrollmentCommandHandler(this.context); var enrollmentResult = await createOrUpdateEnrollmentCommandHandler.Handle(createOrUpdateEnrollmentCommand, CancellationToken.None); enrollmentResult.ShouldBe(true); var query = new GetStudentsWithPassedCoursesQuery(); var handler = new GetStudentsWithPassedCoursesQueryHandler(this.autoMapper, this.context); var result = await handler.Handle(query, CancellationToken.None); result.Where(s => s.Id == createStudentCommand.Id).Count().ShouldBe(1); }
public async Task ShouldBeAbleToGetDetails() { var createStudentCommand = new CreateStudentCommand { FirstName = "satish", LastName = "Venkatakrishnan", EnrollmentDate = DateTime.Now }; var id = await SendAsync(createStudentCommand); var details = await SendAsync(new DetailsModel { Id = id }); details.FirstName.Should().Be("satish"); }
public void TestExecute_PassValidParameters_ShouldCallServiceAddStudentCorrectly() { var parameters = new string[] { "Pesho", " Peshev", "11" }; var mockedStudent = new Mock<IStudent>(); mockedStudent.Setup(t => t.FirstName).Returns(parameters[0]); mockedStudent.Setup(t => t.LastName).Returns(parameters[1]); mockedStudent.Setup(x => x.Grade).Returns((Grade)int.Parse(parameters[2])); var mockedFactory = new Mock<IStudentFactory>(); mockedFactory.Setup(x => x.CreateStudent(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Grade>())) .Returns(mockedStudent.Object); var mockedService = new Mock<ISchoolService>(); mockedService.Setup(s => s.AddStudent(It.IsAny<IStudent>())).Returns(1); var command = new CreateStudentCommand(mockedFactory.Object, mockedService.Object); command.Execute(parameters); mockedService.Verify(x => x.AddStudent(mockedStudent.Object), Times.Once); }