public async Task <ActionResult <Test> > PostTest(TestDto testDto) { var test = _mapper.Map <Test>(testDto); Build build = await _context.FindAsync <Build>(test.Build?.Id); if (build == null) { return(NotFound(new { message = "Invalid Build" })); } test.Build = build; User person = await _context.FindAsync <User>(test.TestPerson?.Id); if (person == null) { return(NotFound(new { message = "Invalid User" })); } test.TestPerson = person; _context.Tests.Add(test); await _context.SaveChangesAsync(); return(CreatedAtAction("GetTest", new { id = test.Id }, test)); }
public bool CreateTest(TestDto testDto) { using var dbContext = _dbContextFactory.GetDbContext(); try { dbContext.Tests.Add(new Test { MinimumSuccessPercentage = testDto.MinimumSuccessPercentage, Subject = testDto.Subject, Quizes = testDto.Quizes.Select(quizDto => new Quiz { Question = quizDto.Question, PointsPerCorrectAnswer = quizDto.PointsPerCorrectAnswer, Complexity = quizDto.Complexity, Options = quizDto.Options.Select(quizOption => new QuizOption { Text = quizOption.Text }).ToList(), CorrectAnswers = quizDto.CorrectAnswers.Select(quizOption => new QuizOption { Text = quizOption.Text }).ToList(), }).ToList() }); dbContext.SaveChanges(); return(true); } catch { return(false); } }
private static void RunTest() { Console.WriteLine("{0}.IsMappableWith({1}) : {2}", typeof(TestViewModel).Name, typeof(TestDto).Name, typeof(TestViewModel).IsMappableWith(typeof(TestDto))); var dto = new TestDto() { DtoId = 20, BirthDate = DateTime.Today, Name = "TestSubject" }; Console.WriteLine("Sample object : {0} / {1} / {2}", dto.DtoId, dto.Name, dto.BirthDate); var vm = dto.MapTo <TestViewModel>(); Console.WriteLine("TestDTo > TestViewModel : {0} / {1} / {2}", vm.Id, vm.Name, vm.BirthDate); vm.Name += "(Modified)"; Console.WriteLine("Changed name to '{0}'.", vm.Name); var newDto = vm.MapTo <TestDto>(); Console.WriteLine("TestViewModel > new TestDto : {0} / {1} / {2}", newDto.DtoId, newDto.Name, newDto.BirthDate); }
public HistoricalCrudServiceDtoTests() { Randomizer.Seed = new Random(1234567); var entityFaker = new Faker <TestEntity>(). RuleFor(_ => _.Id, Guid.NewGuid()). RuleFor(_ => _.Value, _ => _.Lorem.Word()); _entities = entityFaker.Generate(5); _entity = entityFaker.Generate(); var eventFaker = new Faker <HistoricalEvent>(). RuleFor(_ => _.Id, Guid.NewGuid). RuleFor(_ => _.Action, HistoricalActions.Delete.ToString). RuleFor(_ => _.EntityId, _entity.Id). RuleFor(_ => _.Changeset, "{}"); _events = new List <HistoricalEvent>() { eventFaker.Generate() }; var dtoFaker = new Faker <TestDto>(). RuleFor(_ => _.Id, Guid.NewGuid()). RuleFor(_ => _.ValueDto, _ => _.Lorem.Word()); _dtos = dtoFaker.Generate(5); _dto = dtoFaker.Generate(); _mapper = new AutoMapper.MapperConfiguration(_ => { _.CreateMap <TestDto, TestEntity>().ForMember(dest => dest.Value, opts => opts.MapFrom(src => src.ValueDto)); _.CreateMap <TestEntity, TestDto>().ForMember(dest => dest.ValueDto, opts => opts.MapFrom(src => src.Value)); }).CreateMapper(); }
public void UpdateTestEndDate(TestDto testDto, DateTime endTime) { testDto.EndDate = endTime; var test = _mapper.Map <Test>(testDto); _adminRepository.UpdateEndDate(test); }
public void SetObjectLifetimeWithoutIsOk() { var obj = new TestDto(); _cacheService.SetObject("name", "default", obj, "string", 123, null, true, false); _redis.Verify(x => x.ObjectSet("name:string-123--1-0", obj, "default", default, default), Times.Once);
public void Can_optimize_result_with_ToOptimizedResult() { var dto = new TestDto { Name = "test" }; var httpReq = new MockHttpRequest(); httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = "text/html"; var httpRes = new ViewTests.MockHttpResponse(); var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto); var appHost = new TestAppHost(); new HtmlFormat().Register(appHost); EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters; object result = httpRequestContext.ToOptimizedResult(dto); Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); }
internal override DtoBase PopulateDto(OracleDataReader reader) { var test = new TestDto(); // if (!reader.IsDBNull(_ordTstId)) { test.TstId = reader.GetInt32(_ordTstId); } // if (!reader.IsDBNull(_ordTstObservacion)) { test.TstObservacion = reader.GetString(_ordTstObservacion); } // if (!reader.IsDBNull(_ordTstZcuId)) { test.TstZcuId = reader.GetInt32(_ordTstZcuId); } // if (!reader.IsDBNull(_ordTstTptId)) { test.TstTptId = reader.GetInt32(_ordTstTptId); } // IsNew test.IsNew = false; return(test); }
public async Task <TestDto> GetByIdAsync(int id) { Test testEntity = await _unitOfWork.TestRepository.ReadAsync(id); if (testEntity == null) { throw new Exception("Nothing was found by this Id"); } testEntity.Theme = await _unitOfWork.ThemeRepository.ReadAsync(testEntity.ThemeId); TestDto test = testEntity.MapToDto(); List <QuestionDto> questions = new(); IEnumerable <Question> questionEntities = await _unitOfWork.QuestionRepository .GetByConditionAsync(question => question.TestId == testEntity.Id); foreach (var entity in questionEntities) { questions.Add(entity.MapToDto()); } test.Questions = questions; return(test); }
public async Task <ApiResponse> UpdateTestAsync(int testID, TestDto test) { var _test = await _dbContext.Tests.Where(t => t.TestID == testID).SingleOrDefaultAsync(); if (_test != null) { var modifiedData = _mapper.Map <User>(test); modifiedData.UpdatedBy = 1; modifiedData.CreatedOn = _test.CreatedOn; modifiedData.CreatedBy = _test.CreatedBy; modifiedData.UpdatedOn = DateTime.Now; _dbContext.Entry(_test).State = EntityState.Detached; _dbContext.Entry(modifiedData).State = EntityState.Modified; _dbContext.SaveChanges(); return(new ApiResponse { Data = test, Message = "Success", StatusCode = StatusCode.Ok }); } else { return(new ApiResponse { Message = $"Test not found with id {testID}", StatusCode = StatusCode.NotFound }); } }
public void ThrowInvalidTestException_WhenValidTestDtoIsProvided_ButTestIsNotFoundInDb() { //Arrange var mapperMock = new Mock <IMappingProvider>(); var saverMock = new Mock <ISaver>(); var testsMock = new Mock <IRepository <Test> >(); var questionsMock = new Mock <IRepository <Question> >(); var answersMock = new Mock <IRepository <Answer> >(); var userTestsMock = new Mock <IRepository <UserTest> >(); var testsService = new TestsService(saverMock.Object, mapperMock.Object, testsMock.Object, questionsMock.Object, answersMock.Object, userTestsMock.Object); var testDto = new TestDto() { Id = 2 }; var testToEdit = new List <Test>() { new Test { Id = 1 } }; testsMock.Setup(x => x.All).Returns(testToEdit.AsQueryable); //Act & Assert Assert.ThrowsException <InvalidTestException>(() => testsService.Edit(testDto)); }
public void CallTestRepositoryAllMethodOnce_WhenValidTestDtoIsProvided() { //Arrange var mapperMock = new Mock <IMappingProvider>(); var saverMock = new Mock <ISaver>(); var testsMock = new Mock <IRepository <Test> >(); var questionsMock = new Mock <IRepository <Question> >(); var answersMock = new Mock <IRepository <Answer> >(); var userTestsMock = new Mock <IRepository <UserTest> >(); var testsService = new TestsService(saverMock.Object, mapperMock.Object, testsMock.Object, questionsMock.Object, answersMock.Object, userTestsMock.Object); var testDto = new TestDto() { Id = 1, Questions = new List <QuestionDto>() }; var testToEdit = new List <Test>() { new Test { Id = 1 } }; testsMock.Setup(x => x.All).Returns(testToEdit.AsQueryable); //Act testsService.Edit(testDto); //Assert testsMock.Verify(x => x.All, Times.Once); }
public void MappingToDataRow_test() { // this is the mapper var mapper = Mapper.Default.GetMapper <TestDto, DataRow>(new Map2DataRowConfig()); // initialization of test DTO object var testDataObject = new TestDto { Field1 = "field1", Field2 = 10, Field3 = true }; // Initializing of test table. Usual this table is read from database. var dt = new DataTable(); dt.Columns.Add("field1", typeof(string)); dt.Columns.Add("field2", typeof(int)); dt.Columns.Add("field3", typeof(bool)); dt.Rows.Add(); var dr = dt.Rows[0]; // Mapping test object to datarow mapper.Map(testDataObject, dr); // Check if object is correctly mapped dr["field1"].ShouldBe("field1"); dr["field2"].ShouldBe(10); dr["field3"].ShouldBe(true); }
// GET: Tests/Edit/5 public ActionResult Edit(string id) { TestDetailsViewModel model = new TestDetailsViewModel(); TestDto response = webClient.ExecuteGet <TestDto>(new Models.ApiRequest() { EndPoint = string.Format("tests/{0}", id) }); model.AuthToken = response.AuthToken; model.Code = response.Code; model.Name = response.Name; model.Desctiption = response.Description; model.SelectedQuestions = response.Questions.Select(q => new SelectListItem() { Selected = false, Text = q.Text, Value = q.Id.ToString() }).ToList(); model.AvailableQuiestions = webClient.ExecuteGet <IEnumerable <QuestionDto> >(new Models.ApiRequest() { EndPoint = string.Format("questions?skip=0&take={0}", int.MaxValue - 1) }) .Select(q => new SelectListItem() { Selected = false, Text = q.Text, Value = q.Id.ToString() }).ToList(); return(View(model)); }
public async Task <TestDto> GetByIdAsync(int?testId) { var test = await Database.TestRepository.GetByIdAsync(testId); if (test == null) { return(null); } var testDto = new TestDto { Id = test.Id, Name = test.Name, TestDescription = test.TestDescription, Questions = new List <QuestionDto>() }; foreach (var question in test.Questions) { var newQuest = new QuestionDto { Id = question.Id, QuestionContent = question.QuestionContent, Point = question.Point, TestId = question.TestId, Answers = new List <AnswerDto>() }; testDto.Questions.Add(newQuest); } return(testDto); }
/// <summary> /// Ruft PUT /api/test/id mit dem übergebenen Testobjekt auf. /// Löscht danach das Objekt aus der ObservableCollection und fügt das vom Server gelieferte /// neue Testobjekt hinzu. /// </summary> /// <param name="id">Die ID des Testes, die für den HTTP Request verwendet wird.</param> /// <param name="test">Die neuen Daten des Testes.</param> /// <returns></returns> public async Task Update(TestDto test) { TestDto newTest = await RestService.Instance.SendAsync <TestDto>(HttpMethod.Put, "test", test.TestId.ToString(), test); Tests.Remove(test); Tests.Add(newTest); }
public void GetUserTestsMethod_Should_Return_Correct_TestsObject() { // Arrange var result = new UserTest(); var test = new Test(); test.TestName = "Test1"; var category = new Category(); var id = Guid.NewGuid(); test.Category = category; result.UserId = id.ToString(); result.Test = test; var resultDto = new TestDto(); var all = new List <UserTest>() { result }; var results = new List <TestDto>() { resultDto }; resultRepoMock.Setup(x => x.All).Verifiable(); resultRepoMock.Setup(x => x.All).Returns(all.AsQueryable()); mapperMock.Setup(x => x.ProjectTo <TestDto>(It.IsAny <IQueryable <Test> >())).Returns(results.AsQueryable()); // Act var actual = resultService.GetUserResults(id.ToString()); // Assert Assert.AreEqual(resultDto, actual.First()); }
public async Task <ActionResult> CreateTest([Bind(Include = "Id,Name,TestDescription")] TestViewModel testViewModel) { if (ModelState.IsValid) { var testDto = new TestDto { Name = testViewModel.Name, TestDescription = testViewModel.TestDescription, }; try { await TestService.CreateAsync(testDto); return(RedirectToAction("IndexForAdmin")); } catch (TestException e) { ViewBag.Error = e.Message; return(View("Error")); } } return(View(testViewModel)); }
public async Task <ActionResult> Edit([Bind(Include = "Id,Name,TestDescription")] TestViewModel testViewModel) { if (ModelState.IsValid) { var testDto = new TestDto { Id = testViewModel.Id, Name = testViewModel.Name, TestDescription = testViewModel.TestDescription, }; try { await TestService.UpdateAsync(testDto); return(RedirectToAction("Details", "Test", new { id = testViewModel.Id })); } catch (TestException e) { ViewBag.Error = e.Message; return(View("Error")); } } return(View(testViewModel)); }
public void Can_get_test_details() { #region Arrange var test = new TestDto { Author = ProfileModelDto.Map(TestPofile), CreationDate = DateTime.Now, Name = "new test", TestType = TestTypeModelDto.Map(TestTestType), Questions = new List <TestQuestionModelDto> { TestQuestionModelDto.Map(TestQuestion) } }; using (var session = DataAccess.OpenSession()) { var course = session.Get <CourseModel>(1); course.Tests.Add(TestDto.UnMap(test)); session.Flush(); } #endregion #region Act test = new TestService().GetTestDetails(3); #endregion #region Assert Assert.That(test.Name, Is.EqualTo("new test")); Assert.That(test.Questions.Count, Is.EqualTo(1)); Assert.That(test.Questions.First().Answers.Count, Is.EqualTo(1)); #endregion }
public void SetTheTestEntityModelStatusIdToOne_WhenValidTestDtoProvided() { //Arrange var mapperMock = new Mock <IMappingProvider>(); var saverMock = new Mock <ISaver>(); var testsMock = new Mock <IRepository <Test> >(); var questionsMock = new Mock <IRepository <Question> >(); var answersMock = new Mock <IRepository <Answer> >(); var userTestsMock = new Mock <IRepository <UserTest> >(); var sut = new TestsService(saverMock.Object, mapperMock.Object, testsMock.Object, questionsMock.Object, answersMock.Object, userTestsMock.Object); var testDto = new TestDto(); var test = new Test() { StatusId = 1 }; mapperMock.Setup(x => x.MapTo <Test>(It.IsAny <TestDto>())).Returns(test); //Act sut.SaveAsDraft(testDto); //Assert Assert.AreEqual(2, test.StatusId); }
public async Task <OperationResult <Dtos.Test.TestDto> > GetTest(int testId) { var test = await dbContext.ScheduledTests .Include(x => x.TestTemplate) .ThenInclude(x => x.TestItems) .ThenInclude(x => x.Question) .ThenInclude(x => x.Answer) .ThenInclude(x => ((ChoiceAnswer)x).Choices) .Where(x => x.Id == testId) .FirstOrDefaultAsync(); if (test == null) { return(new DataNotFoundError()); } var dto = new TestDto { Name = test.TestTemplate.Name, Duration = test.Duration, Questions = test.TestTemplate.TestItems.Select(x => questionMapper.MapToTestQuestionDto(x.Question)).ToList() }; return(dto); }
public ActionResult AddTest(TestVm model) { if (ModelState.IsValid) { var dbTest = _baseTestService.GetTestByNumber(model.Number); if (dbTest != null) { ModelState.AddModelError(nameof(model.Number), "Test o podanym numerze już istnieje."); return(View(model)); } //automatically set start and end time var testDay = model.StartDate; model.StartDate = testDay.AddHours(12).AddMinutes(00); model.EndDate = testDay.AddHours(23).AddMinutes(59); var testDto = new TestDto { Number = model.Number, Description = model.Description, Answer = model.Answer.ToUpper().Replace(" ", ""), StartDate = model.StartDate, EndDate = model.EndDate, SponsorLogoUrl = model.SponsorLogoUrl, SponsorName = model.SponsorName, Discount = model.Discount, DiscountUrl = model.DiscountUrl, DiscountLogoUrl = model.DiscountLogoUrl, DiscountLogoPath = model.DiscountLogoPath }; _adminService.AddTest(testDto); return(RedirectToAction("Index")); } return(View(model)); }
private static void CanOptimizeResult(string contentType, IPlugin pluginFormat) { using var appHost = new BasicAppHost().Init(); var dto = new TestDto { Name = "test" }; var httpReq = new MockHttpRequest { PathInfo = "/" }; httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = contentType; if (pluginFormat != null) { pluginFormat.Register(appHost); } #pragma warning disable CS0618 object result = httpReq.ToOptimizedResult(dto); #pragma warning restore CS0618 Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); }
public void 指定型別() { Dapper.SqlMapper.AddTypeHandler(new VarcharToNullDecimalHandler()); var sql = @" DECLARE @TmpTable TABLE ( [Column1] VARCHAR(50) ) INSERT INTO @TmpTable(Column1) VALUES (@Column1) SELECT * FROM @TmpTable "; var dbConnection = DiFactory.GetService <IDbConnection>(); var dto = new TestDto { Column1 = 1.234m, }; var param = new DynamicParameters(); param.Add("Column1", dto.Column1, DbType.AnsiString); var result = dbConnection.QueryFirstOrDefault <TestDto>(sql, param); Assert.AreEqual(result.Column1, 1.234m); }
public void BasicEquivalence() { var empty = new TestDto(); var full = new TestDto { Id = 3, Name = "Three", Children = new[] { new TestDto { Name = "child" } } }; empty.IsEquivalentTo(null).Should().BeFalse(); empty.IsEquivalentTo(empty).Should().BeTrue(); empty.IsEquivalentTo(new TestDto()).Should().BeTrue(); empty.IsEquivalentTo(full).Should().BeFalse(); full.IsEquivalentTo(new TestDto { Id = 3 }).Should().BeFalse(); full.IsEquivalentTo(null).Should().BeFalse(); full.IsEquivalentTo(empty).Should().BeFalse(); full.IsEquivalentTo(new TestDto { Id = 3, Name = "Three", Children = new[] { new TestDto { Name = "child" } } }).Should().BeTrue(); full.IsEquivalentTo(full).Should().BeTrue(); full.IsEquivalentTo(new TestDto { Id = 3 }).Should().BeFalse(); }
public void CallShufflerShuffleAnswers_WithCorrectParameter() { // Arrange var answersDto = new List <AnswerDto>(); var questionsDto = new List <QuestionDto>() { new QuestionDto() { Answers = answersDto } }; var testDto = new TestDto() { Questions = questionsDto }; this.shufflerMock.Setup(x => x.Shuffle <QuestionDto>(It.IsAny <List <QuestionDto> >())) .Returns(questionsDto); this.shufflerMock.Setup(x => x.Shuffle <AnswerDto>(It.IsAny <List <AnswerDto> >())) .Returns(answersDto); var sut = new TestService(testRepoMock.Object, questionRepoMock.Object, answerRepoMock.Object, dataSaverMock.Object, mapperMock.Object, categoryRepoMock.Object, randomMock.Object, shufflerMock.Object, memoryCacheMock.Object); // act sut.ShuffleTest(testDto); // Assert this.shufflerMock.Verify(x => x.Shuffle <AnswerDto>(testDto.Questions[0].Answers), Times.Once); }
public void ChangeTestQuestionState_WhenCalledWithValidArgument() { // Arrange var testQuestionsDto = new List <QuestionDto>(); var testDto = new TestDto() { Questions = testQuestionsDto }; var testsDomainDto = new List <TestDto>() { testDto }; this.shufflerMock.Setup(x => x.Shuffle <QuestionDto>(It.IsAny <List <QuestionDto> >())) .Returns(new List <QuestionDto>()); var sut = new TestService(testRepoMock.Object, questionRepoMock.Object, answerRepoMock.Object, dataSaverMock.Object, mapperMock.Object, categoryRepoMock.Object, randomMock.Object, shufflerMock.Object, memoryCacheMock.Object); // Act sut.ShuffleTest(testDto); // Assert Assert.AreNotEqual(testQuestionsDto, testDto.Questions); }
public TestDto Get(string id) { TestDto test = null; using (SqlConnection sqlConnection = new SqlConnection(_connectionString)) { using (SqlCommand sqlCommand = new SqlCommand("GetTest", sqlConnection)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add("@id", SqlDbType.Int).Value = id; sqlConnection.Open(); using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection)) { while (sqlDataReader.Read()) { string question = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Question")); test = new TestDto() { Id = id, Question = question, }; } sqlDataReader.Close(); } } } return(test); }
private static void CanOptimizeResult(string contentType, IPlugin pluginFormat) { var dto = new TestDto { Name = "test" }; var httpReq = new MockHttpRequest(); httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = contentType; var httpRes = new ViewTests.MockHttpResponse(); var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto); var appHost = new TestAppHost(); if (pluginFormat != null) { pluginFormat.Register(appHost); } EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters; object result = httpRequestContext.ToOptimizedResult(dto); Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); }
public void Indexed_enum_property() { var message = new TestDto(); message.Options[TestEnum.EnumValue1]["test"] = "aString"; inspector.ScanObject(message); }
public void ValidateElementsMandatoryContext() { var good = new TestDto() { StringList = new[] { "abcde" } }; var results = new List<ValidationResult>(); Assert.Throws<ArgumentNullException>(() => Validator.TryValidateObject(good, null, results)); }
public IHttpActionResult AddTest(TestDto test) { try { int id = _testService.AddTest(test); return Ok(id); } catch (Exception ex) { return BadRequest(ex.Message); } }
public void Indexed_enum_property() { var message = new TestDto(); var dict = message.Options[TestEnum.EnumValue1]; dict["test"] = "asdf"; message.Options[TestEnum.EnumValue1]["test"] = "asdf"; var result = (TestDto)mutator.MutateOutgoing(message); Assert.True(result.Options.ContainsKey(TestEnum.EnumValue1)); }
public void BasicTest() { var good = new TestDto() { StringList = new[] { "abcde" } }; var bad = new TestDto() { StringList = new[] { "a" } }; ExtendedValidator.EnsureIsValid(good); Assert.Throws<AggregateValidationException>(() => ExtendedValidator.EnsureIsValid(bad)); }
public void PropertyCollectionChange_DtoPropertyCollectionChanged_AddsToCollectionAndRaisesPropertyChanged() { var dto = new TestDto () { PropertyCollectionDtos = new ObservableCollection<PropertyCollectionDto> () }; IList<PropertyCollectionDto> collectionDtos = new List<PropertyCollectionDto> () { new PropertyCollectionDto { Key = 1, Name = "First" }, new PropertyCollectionDto { Key = 2, Name = "Second" } }; bool propertyChanged = false; dto.PropertyChanged += ( s, e ) => { propertyChanged = true; }; dto.PropertyCollectionDtos = new ObservableCollection<PropertyCollectionDto> ( collectionDtos ); Assert.AreEqual ( dto.PropertyCollectionDtos.Count, collectionDtos.Count ); Assert.IsTrue ( propertyChanged ); }
public void TestAutoMapperPrivatePropertyMapping() { Mapper.CreateMap<TestDto, TestClassPrivateSetters>(); var dto = new TestDto() { Description = "Foo bar...", Number = 339.38M, }; var result = Mapper.Map<TestClassPrivateSetters>(dto); Assert.AreEqual(dto.Number, result.Number); Assert.AreEqual(dto.Description, result.Description); }
public void PropertyChange_DtoPropertyNotChanged_NoChangeInValueAndPropertyChangedIsNotRaised() { var dto = new TestDto (); var propertyDto = new PropertyDto { Key = 1, Name = "Test" }; bool propertyChanged = false; dto.PropertyChanged += ( s, e ) => { propertyChanged = true; }; dto.PropertyDto = propertyDto; Assert.AreEqual ( dto.PropertyDto, propertyDto ); Assert.IsTrue ( propertyChanged ); propertyChanged = false; dto.PropertyDto = propertyDto; Assert.AreEqual ( dto.PropertyDto, propertyDto ); Assert.IsFalse ( propertyChanged ); }
public void Can_add_test() { #region Arrange var test = new TestDto { Author= ProfileModelDto.Map(TestPofile), CreationDate=DateTime.Now, Name="new test" , TestType= TestTypeModelDto.Map(TestTestType)}; #endregion #region Act new TestService().AddTestToCourse(1, test); //var tests= new CourseService().GetAllTestsSignatures(1); #endregion #region Assert //Assert.That(tests.Count,Is.EqualTo(1)); //Assert.That(tests.First().Name, Is.EqualTo("new test")); #endregion }
public void PropertyChange_DtoPropertyChanged_SetsNewValueAndRaisesPropertyChanged() { var dto = new TestDto (); var propertyDto1 = new PropertyDto { Key = 1, Name = "Test1" }; var propertyDto2 = new PropertyDto { Key = 2, Name = "Test2" }; bool propertyChanged = false; dto.PropertyChanged += ( s, e ) => { propertyChanged = true; }; dto.PropertyDto = propertyDto1; Assert.AreEqual ( dto.PropertyDto, propertyDto1 ); Assert.IsTrue ( propertyChanged ); propertyChanged = false; dto.PropertyDto = propertyDto2; Assert.AreEqual ( dto.PropertyDto, propertyDto2 ); Assert.IsTrue ( propertyChanged ); }
private static void CanOptimizeResult(string contentType, IPlugin pluginFormat) { using (var appHost = new BasicAppHost().Init()) { var dto = new TestDto { Name = "test" }; var httpReq = new MockHttpRequest(); httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = contentType; if (pluginFormat != null) pluginFormat.Register(appHost); object result = httpReq.ToOptimizedResult(dto); Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); } }
public int AddTest(TestDto newTestDto) { Test test = new Test(); newTestDto.ToTest(test); try { _testRepository.UpdateAndCommit(test); _unitOfWork.SaveChanges(); return test.Id; } catch (Exception ex) { _logger.Log(ex); throw ex; } }
public void Can_optimize_result_with_ToOptimizedResult() { var dto = new TestDto {Name = "test"}; var httpReq = new MockHttpRequest(); httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = "text/html"; var httpRes = new ViewTests.MockHttpResponse(); var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto); var appHost = new TestAppHost(); HtmlFormat.Register(appHost); EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters; object result = httpRequestContext.ToOptimizedResult(dto); Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); }
private static void CanOptimizeResult(string contentType, IPlugin pluginFormat) { var dto = new TestDto {Name = "test"}; var httpReq = new MockHttpRequest(); httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch"); httpReq.ResponseContentType = contentType; var httpRes = new ViewTests.MockHttpResponse(); var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto); var appHost = new TestAppHost(); if (pluginFormat != null) pluginFormat.Register(appHost); EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters; object result = httpRequestContext.ToOptimizedResult(dto); Assert.IsNotNull(result); Assert.IsTrue(result is CompressedResult); }
public int AddTestToCourse(int courseId,TestDto test) { try { var id = -1; DataAccess.InTransaction(session => { var course = session.Get<CourseModel>(courseId); var model = TestDto.UnMap(test); id = (int)session.Save(model); course.Tests.Add(model); session.Save(course); }); Logger.Trace("Created Test id - {0}", id); return id; } catch (Exception ex) { Logger.Error("Error : AddTestToCourse - {0}", ex.Message); return -1; } }
public void Can_update_test() { #region Arrange var test = new TestDto { Author = ProfileModelDto.Map(TestPofile), CreationDate = DateTime.Now, Name = "new test", TestType = TestTypeModelDto.Map(TestTestType) }; using (var session = DataAccess.OpenSession()) { var course = session.Get<CourseModel>(1); course.Tests.Add(TestDto.UnMap(test)); session.Flush(); } using (var session = DataAccess.OpenSession()) { var course = session.Get<CourseModel>(1); Assert.That(course.Tests[0].Name, Is.EqualTo("new test")); test.ID = course.Tests[0].ID; } #endregion #region Act test.Name = "updated test"; bool updateOk = new TestService().UpdateTest(test); #endregion #region Assert using (var session = DataAccess.OpenSession()) { var course = session.Get<CourseModel>(1); Assert.That(course.Tests[0].Name, Is.EqualTo("updated test")); Assert.That(updateOk,Is.True); } #endregion }
public int AddTestToLearningMaterial(int learningMaterialId, TestDto test) { try { var id = -1; DataAccess.InTransaction(session => { var learningMaterial = session.Get<LearningMaterialModel>(learningMaterialId); var model = TestDto.UnMap(test); id = (int)session.Save(model); learningMaterial.Tests.Add(model); session.Save(learningMaterial); }); Logger.Trace("Created Test id - {0}", id); return id; } catch (Exception ex) { Logger.Error("Error : AddTestToLearningMaterial - {0}", ex.Message); return -1; } }
public bool UpdateTest(TestDto test) { try { DataAccess.InTransaction(session => session.Update(TestDto.UnMap(test))); return true; } catch (Exception ex) { Logger.Error("Error : TestService.UpdateTest - {0}", ex.Message); return false; } }
public void UpdateTest(TestDto newTestDto) { Test test = new Test(); newTestDto.ToTest(test); try { _testRepository.Update(test); _unitOfWork.SaveChanges(); } catch (Exception ex) { _logger.Log(ex); throw ex; } }
public void CanPopulatePropertiesOfTypeDecimal() { var dto = new TestDto(); _testDtoConverter.PopulateProperty(dto, "Field4", "185.743725183137"); Assert.AreEqual(185.743725183137d, dto.Field4); }
public void Can_get_test_details() { #region Arrange var test = new TestDto { Author = ProfileModelDto.Map(TestPofile), CreationDate = DateTime.Now, Name = "new test", TestType = TestTypeModelDto.Map(TestTestType), Questions =new List<TestQuestionModelDto>{ TestQuestionModelDto.Map(TestQuestion)} }; using (var session = DataAccess.OpenSession()) { var course = session.Get<CourseModel>(1); course.Tests.Add(TestDto.UnMap(test)); session.Flush(); } #endregion #region Act test =new TestService().GetTestDetails(3); #endregion #region Assert Assert.That(test.Name, Is.EqualTo("new test")); Assert.That(test.Questions.Count,Is.EqualTo(1)); Assert.That(test.Questions.First().Answers.Count, Is.EqualTo(1)); #endregion }
public void CanPopulatePropertiesOfTypeString() { var dto = new TestDto(); _testDtoConverter.PopulateProperty(dto, "Field1", "stringValue"); Assert.AreEqual("stringValue", dto.Field1); }
public void CanPopulatePropertiesOfTypeDateTime() { var dto = new TestDto(); _testDtoConverter.PopulateProperty(dto, "Field3", @"\/Date(1295580161923)\/"); Assert.AreEqual("2011-01-21 03:22:41Z", dto.Field3.ToString("u")); }
public void CanPopulatePropertiesOfTypeInt() { var dto = new TestDto(); _testDtoConverter.PopulateProperty(dto, "Field2", "42"); Assert.AreEqual(42, dto.Field2); }
public IHttpActionResult UpdateTest(TestDto test) { try { _testService.UpdateTest(test); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } }