public static List<SampleEntity> SetUpSampleEntities(dynamic message) { var entitys = new List<SampleEntity>(); var entity1 = new SampleEntity() { CreatedDate = DateTime.Now.AddMonths(-1).ToUniversalTime(), Id = message.Needs[0].SampleUuid.ToString(), NewDecimalValue = 123.45M, NewGuidValue = Guid.NewGuid(), NewIntValue = 1, NewStringValue = "Test", UpdatedDate = DateTime.Now.AddHours(-6).ToUniversalTime() }; var entity2 = new SampleEntity() { CreatedDate = DateTime.Now.AddMonths(-1).ToUniversalTime(), Id = Guid.NewGuid().ToString(), NewDecimalValue = 123.45M, NewGuidValue = Guid.NewGuid(), NewIntValue = 1, NewStringValue = "Test", UpdatedDate = DateTime.Now.AddHours(-6).ToUniversalTime() }; entitys.Add(entity1); entitys.Add(entity2); return entitys; }
public void MethodInTransactionShouldSucceed(SampleEntity entity) { RunInTransaction(() => { sampleEntityDao.Insert(entity); }); }
public void MethodInTransactionShouldAbort(SampleEntity entity) { RunInTransaction(() => { sampleEntityDao.Insert(entity); throw new Exception("An Exception"); }); }
public void NoRowsAffectedDeleteTest() { var sampleEntityDao = Container.Resolve<SampleEntityDao>(); var sampleEntity = new SampleEntity() { Id = 10, StringProperty = "ABC" }; Assert.Throws<NoRowsAffectedException>(() => sampleEntityDao.Delete(sampleEntity)); }
public void MappedQuery_Any_False() { var query = new SampleEntity[0].AsQueryable().AsMappedQuery( new DelegatedMapper<SampleEntity, SampleDto>(t => new SampleDto { Property1 = t.Property1, Property2 = t.Property2 })); query.Any().Should().BeFalse(); }
public void GetHashCodeShouldBeEqaulToResharperGenerated(int id, int? nullable, string name) { var provider = new Mock<IObjectPropertyProvider>(); var props = typeof(SampleEntity).GetProperties(); provider.Setup(x => x.GetProperties<SampleEntity>()).Returns(props); provider.Setup(x => x.GetPrimaryKeyProperties<SampleEntity>()).Returns(new List<PropertyInfo>()); var factory = new EqualityComparerFactory(provider.Object); var comparer = factory.CreateCompleteComparer<SampleEntity>(); var left = new SampleEntity { Id = id, NullableId = nullable, Name = name }; Assert.That(comparer.GetHashCode(left), Is.EqualTo(left.GetHashCode())); }
public void ValidationExceptionIsRaised2() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = null, Names = new List<string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id, handleAsError: false); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); val.RaiseIfHasIssues(); }
public void ValidationExceptionIsRaised1() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = null, Names = new List<string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); val.RaiseWhenFailed(); }
public void DeleteTest() { var sampleEntityDao = Container.Resolve<SampleEntityDao>(); var sampleEntity = new SampleEntity() { StringProperty = "1" }; sampleEntityDao.Insert(sampleEntity); var primaryKeyId = sampleEntity.Id; sampleEntityDao.Delete(sampleEntity); Assert.Throws<EmptyResultDataAccessException>(() => sampleEntityDao.Get(primaryKeyId)); }
public void then_merge_updated_entities_are_found() { List <SampleEntity> actualList = SampleDatabase.SampleEntities .Where(x => x.StringProperty == _testName) .OrderBy(x => x.Id) .ToList(); for (int i = 0; i < _insertedItems.Count; i++) { SampleEntity expectedItem = _insertedItems[i]; SampleEntity actualItem = actualList[i]; expectedItem.Id = actualItem.Id; expectedItem.Should().BeEquivalentTo(actualItem); } }
public void ValidationExceptionIsNotRaised1() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = null, Names = new List<string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id, handleAsError: false); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); val.RaiseWhenFailed(); // --- Assert: there is no exception }
public void GetHashCodeShouldBeEqaulToResharperGenerated(int id, int?nullable, string name) { var provider = new Mock <IObjectPropertyProvider>(); var props = typeof(SampleEntity).GetProperties(); provider.Setup(x => x.GetProperties <SampleEntity>()).Returns(props); provider.Setup(x => x.GetPrimaryKeyProperties <SampleEntity>()).Returns(new List <PropertyInfo>()); var factory = new EqualityComparerFactory(provider.Object); var comparer = factory.CreateCompleteComparer <SampleEntity>(); var left = new SampleEntity { Id = id, NullableId = nullable, Name = name }; Assert.That(comparer.GetHashCode(left), Is.EqualTo(left.GetHashCode())); }
public void UseSpecificationAndOperatorTest() { //Arrange DirectSpecification <SampleEntity> leftAdHocSpecification; DirectSpecification <SampleEntity> rightAdHocSpecification; var identifier = Guid.NewGuid(); Expression <Func <SampleEntity, bool> > leftSpec = s => s.Id == identifier; Expression <Func <SampleEntity, bool> > rightSpec = s => s.SampleProperty.Length > 2; //Act leftAdHocSpecification = new DirectSpecification <SampleEntity>(leftSpec); rightAdHocSpecification = new DirectSpecification <SampleEntity>(rightSpec); ISpecification <SampleEntity> andSpec = leftAdHocSpecification && rightAdHocSpecification; var list = new List <SampleEntity>(); var sampleA = new SampleEntity() { SampleProperty = "1" }; sampleA.ChangeCurrentIdentity(identifier); var sampleB = new SampleEntity() { SampleProperty = "the sample property" }; sampleB.GenerateNewIdentity(); var sampleC = new SampleEntity() { SampleProperty = "the sample property" }; sampleC.ChangeCurrentIdentity(identifier); list.AddRange(new SampleEntity[] { sampleA, sampleB, sampleC }); var result = list.AsQueryable().Where(andSpec.SatisfiedBy()).ToList(); Assert.True(result.Count == 1); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. // This class contains the application-specific WebJob code consisting of event-driven // methods executed when messages appear in queues with any supporting code. // Trigger method - run when new message detected in queue. "thumbnailmaker" is name of queue. // "photogallery" is name of storage container; "images" and "thumbanils" are folder names. // "{queueTrigger}" is an inbuilt variable taking on value of contents of message automatically; // the other variables are valued automatically. public static void GenerateSample( [QueueTrigger("samples")] SampleEntity sampleEntity, TextWriter logger) { //use log.WriteLine() rather than Console.WriteLine() for trace output CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString()); logger.WriteLine("GenerateThumbnail() started..."); logger.WriteLine(sampleEntity.RowKey); CloudTable table = storageAccount.CreateCloudTableClient().GetTableReference("Samples"); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer videoContainer = blobClient.GetContainerReference("original"); videoContainer.CreateIfNotExists(); TableOperation retriveOperation = TableOperation.Retrieve <SampleEntity>("Samples_Partition_1", sampleEntity.RowKey);; TableResult getOperationResult = table.Execute(retriveOperation); if (getOperationResult.Result == null) { return; } SampleEntity sample = (SampleEntity)getOperationResult.Result; CloudBlockBlob blob = videoContainer.GetBlockBlobReference(sample.Mp4Blob); logger.WriteLine(sample.SampleMp4URL); string fileName = Guid.NewGuid().ToString(); CloudBlockBlob outputBlob = videoContainer.GetBlockBlobReference(fileName); using (Stream input = blob.OpenRead()) using (Stream output = outputBlob.OpenWrite()) { CropVideo(input, output); outputBlob.Properties.ContentType = "video/mp4"; } sample.SampleDate = DateTime.Now; sample.SampleMp4Blob = fileName; TableOperation tableOp = TableOperation.Replace(sample); table.Execute(tableOp); logger.WriteLine("GenerateVideo() completed"); }
//[Test] public void CreateQueryShouldReturnInsertIntoStatement() { // Given var entity = new SampleEntity() { sampleInt = 1, sampleStr = "str", sampleBool = true, sampleDateTime = DateTime.Now }; var dapperQueryBuilder = new DapperQueryBuilder <SampleEntity>(); // When var query = dapperQueryBuilder.CreateQuery(entity); // Then Assert.AreEqual($"insert into samples(sampleint, samplestr, samplebool, sampledatetime, guid, isactive, isdeleted, createdat, createduserid, updatedat, updateduserid) values(1, 'str', True, '{DateTime.Now}', False, False, '{DateTime.Now}', 0, '{DateTime.Now}', 0) returning id", query); }
public async Task CheckWriteIsNotRestoreDeletedEntityAsync() { var entity = new SampleEntity { Id = Guid.NewGuid(), SomeData = "testData" }; await storage.WriteAsync(entity); await storage.RemoveAsync(entity); await storage.WriteAsync(entity); var readedEntity = await storage.ReadAsync(entity.Id); Assert.IsTrue(readedEntity.IsDeleted); }
public static List<SampleEntity> SetUpSampleEntityFromMessage(dynamic message) { var entitys = new List<SampleEntity>(); var entity1 = new SampleEntity() { CreatedDate = DateTime.Now.AddMonths(-1).ToUniversalTime(), Id = message.Needs[0].SampleUuid.ToString(), NewDecimalValue = message.Needs[0].NewDecimalValue, NewGuidValue = message.Needs[0].NewGuidValue, NewIntValue = message.Needs[0].NewIntValue, NewStringValue = message.Needs[0].NewStringValue, UpdatedDate = DateTime.Now.AddMonths(-1).ToUniversalTime() }; entitys.Add(entity1); return entitys; }
private void deleteOldBlobs(SampleEntity sample) { // Delete previous original and sample blobs if they exist CloudBlobContainer videoContainer = blobClient.GetContainerReference("original"); if (sample.Mp4Blob != null) { CloudBlockBlob blob = videoContainer.GetBlockBlobReference(sample.Mp4Blob); blob.DeleteIfExists(); sample.Mp4Blob = null; } if (sample.SampleMp4Blob != null) { CloudBlockBlob blob = videoContainer.GetBlockBlobReference(sample.SampleMp4Blob); blob.DeleteIfExists(); sample.SampleMp4URL = null; } }
public void SampleUseRepositoryUpdate() { var db = GetMockDB(); var rep = new Repository.Model.Repository(db); var entity = new SampleEntity() { id = 1, iValue = 2, mValue = 2m, sValue = "2" }; rep.Update(entity); Assert.Equal(3, db.Samples.Count); Assert.Equal(entity, db.Samples.First(n => n.id == 1)); }
public async void SaveEntityAsync_Passes_Entity_And_Params() { //arrange. var entity = new SampleEntity { _id = "id123", _rev = "rev123", Name = "somename", Name2 = 213 }; var entityJson = JsonConvert.SerializeObject(entity); var updateParams = new DocUpdateParams(); _db.Setup(db => db.SaveStringDocumentAsync(It.IsAny <string>(), It.IsAny <DocUpdateParams>())) .Returns(Task.FromResult(new SaveDocResponse(new CouchDBDatabase.SaveDocResponseDTO()))); //act. await _sut.SaveEntityAsync(entity, updateParams); //assert. _db.Verify(db => db.SaveStringDocumentAsync(It.Is <string>(str => StringIsJsonObject(str, JObject.Parse(entityJson))), updateParams), Times.Once()); }
public void DiferentIdProduceEqualsFalseTest() { //Arrange var entityLeft = new SampleEntity(); var entityRight = new SampleEntity(); entityLeft.GenerateNewIdentity(); entityRight.GenerateNewIdentity(); //Act bool resultOnEquals = entityLeft.Equals(entityRight); bool resultOnOperator = entityLeft == entityRight; //Assert Assert.False(resultOnEquals); Assert.False(resultOnOperator); }
public async Task <bool> SaveAsync(SampleEntity entity) { string eTag = null; var dbEntity = entity as SampleEntityExtension; if (dbEntity == null) { dbEntity = SampleEntityExtension.FromSampleEntity(entity); } else { eTag = dbEntity.ETag; } var result = await repository.SaveAsync(entity.Id.ToString(), entity.OwnerId.ToString(), dbEntity, eTag); return(result.IsSuccessful); }
public void WithSetup_does_not_use_transaction_when_specified_not_to([Frozen] IGetsSession sessionProvider, PersistenceTestBuilder sut, [NoRecursion] SampleEntity entity, ISession session, ITransaction tran) { Mock.Get(sessionProvider).Setup(x => x.GetSession()).Returns(session); Mock.Get(session).Setup(x => x.BeginTransaction()).Returns(tran); var action = GetSetup(getter => { /* Noop */ }); var result = (PersistenceTestBuilder <SampleEntity>)AsSetupChooser(sut) .WithSetup(action, false) .WithEntity(entity); result.Setup(sessionProvider); Mock.Get(session).Verify(x => x.BeginTransaction(), Times.Never); }
public void WithEqualityRule_uses_rule_in_spec(IGetsEqualityResult <SampleEntity> equalityRule, IGetsSession sessionProvider, [NoRecursion] SampleEntity entity, ITestsPersistence <SampleEntity> tester) { Mock.Get(tester).Setup(x => x.GetTestResult()).Returns(() => null); PersistenceTestSpec <SampleEntity> specification = null; var builder = new PersistenceTestBuilder <SampleEntity>(sessionProvider, entity, null, spec => { specification = spec; return(tester); }); var sut = AsComparerChooser(builder); sut.WithEqualityRule(equalityRule); Assert.That(specification?.EqualityRule, Is.SameAs(equalityRule)); }
public IActionResult UpdateSampleEntities() { try { var sampleEntity = new SampleEntity(); sampleEntity.Id = Guid.Parse("D4B98C2C-46DE-4A2A-9335-5735851F28EF"); sampleEntity.FullName = "Madan kumar Mallik"; sampleEntity.Age = 96; var retVal = _sampleBusinessManager.Update(sampleEntity.Id, sampleEntity); return(this.Ok(retVal)); } catch (Exception ex) { _log.Error(ExceptionFormatter.SerializeToString(ex)); return(StatusCode((int)HttpStatusCode.InternalServerError, ApiConstant.CustomErrorMessage)); } }
public void CompareTheSameReferenceReturnTrueTest() { //Arrange var entityLeft = new SampleEntity(); SampleEntity entityRight = entityLeft; //Act if (!entityLeft.Equals(entityRight)) { Assert.Fail(); } if (!(entityLeft == entityRight)) { Assert.Fail(); } }
public IHttpActionResult PutSample(string id, Sample sample) { if (id != sample.SampleID) { return(BadRequest()); } // Create a retrieve operation that takes a product entity. TableOperation retrieveOperation = TableOperation.Retrieve <SampleEntity>(partitionName, id); // Execute the operation. TableResult retrievedResult = table.Execute(retrieveOperation); // Assign the result to a ProductEntity object. SampleEntity updateEntity = (SampleEntity)retrievedResult.Result; String mp3Sample = updateEntity.SampleMp3Blob; deleteOldSampleBlobs(mp3Sample); updateEntity.Title = sample.Title; updateEntity.Artist = sample.Artist; updateEntity.CreatedDate = sample.CreatedDate; updateEntity.Mp3Blob = sample.Mp3Blob; updateEntity.SampleMp3Blob = sample.SampleMp3Blob; updateEntity.SampleMp3URL = sample.SampleMp3URL; var JsonSam = JsonConvert.SerializeObject(updateEntity); getSoundbiteMakerQueue().AddMessage(new CloudQueueMessage(JsonSam)); // Create the TableOperation that inserts the product entity. // Note semantics of InsertOrReplace() which are consistent with PUT // See: https://stackoverflow.com/questions/14685907/difference-between-insert-or-merge-entity-and-insert-or-replace-entity var updateOperation = TableOperation.InsertOrReplace(updateEntity); // Execute the insert operation. table.Execute(updateOperation); return(StatusCode(HttpStatusCode.NoContent)); }
public void CreateOrSpecificationTest() { //Arrange DirectSpecification <SampleEntity> leftAdHocSpecification; DirectSpecification <SampleEntity> rightAdHocSpecification; var identifier = Guid.NewGuid(); Expression <Func <SampleEntity, bool> > leftSpec = s => s.Id == identifier; Expression <Func <SampleEntity, bool> > rightSpec = s => s.SampleProperty.Length > 2; leftAdHocSpecification = new DirectSpecification <SampleEntity>(leftSpec); rightAdHocSpecification = new DirectSpecification <SampleEntity>(rightSpec); //Act OrSpecification <SampleEntity> composite = new OrSpecification <SampleEntity>(leftAdHocSpecification, rightAdHocSpecification); //Assert Assert.IsNotNull(composite.SatisfiedBy()); Assert.ReferenceEquals(leftAdHocSpecification, composite.LeftSideSpecification); Assert.ReferenceEquals(rightAdHocSpecification, composite.RightSideSpecification); var list = new List <SampleEntity>(); var sampleA = new SampleEntity() { SampleProperty = "1" }; sampleA.ChangeCurrentIdentity(identifier); var sampleB = new SampleEntity() { SampleProperty = "the sample property" }; sampleB.GenerateNewIdentity(); list.AddRange(new SampleEntity[] { sampleA, sampleB }); var result = list.AsQueryable().Where(composite.SatisfiedBy()).ToList(); Assert.IsTrue(result.Count() == 2); }
public void ValidatorWorksAsExpected3() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = 12, Names = new List <string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); // --- Assert val.HasError.ShouldBeFalse(); }
public void GetTestResult_records_error_if_save_returns_null([Frozen] ISession session, [Frozen] ITransaction tran, [Frozen, NoRecursion] SampleEntity entity, [NoAutoProperties] PersistenceTestSpec <SampleEntity> spec) { var sut = new PersistenceTester <SampleEntity>(spec); Mock.Get(spec.SessionProvider).Setup(x => x.GetSession()).Returns(session); Mock.Get(session) .Setup(x => x.BeginTransaction()) .Returns(tran); Mock.Get(session) .Setup(x => x.Save(entity)) .Returns(() => null); var result = sut.GetTestResult(); Assert.That(result?.SaveException, Is.InstanceOf <InvalidOperationException>()); }
public void Test_GetAll() { // Arrange var repository = new SampleEntityRepository(); var newEntity1 = new SampleEntity(1, Guid.NewGuid().ToString()); var newEntity2 = new SampleEntity(2, Guid.NewGuid().ToString()); repository.ExportedListForTest.Add(newEntity1); repository.ExportedListForTest.Add(newEntity2); // Act var savedEntities = repository.GetAll(); // Arrange Assert.NotNull(savedEntities); savedEntities.Count().Equals(2); Assert.Contains(savedEntities, x => x.Id == newEntity1.Id && x.Name == newEntity1.Name); Assert.Contains(savedEntities, x => x.Id == newEntity2.Id && x.Name == newEntity2.Name); }
public void then_inserted_entities_in_transaction_are_saved() { List <SampleEntity> actualList = SampleDatabase.SampleEntities .Where(x => x.StringProperty == _testName) .OrderBy(x => x.Id) .ToList(); actualList.Count.ShouldEqual(_insertedItems.Count); for (int i = 0; i < _insertedItems.Count; i++) { SampleEntity actualItem = actualList[i]; SampleEntity expectedItem = _insertedItems[i]; expectedItem.Id = actualItem.Id; expectedItem.ShouldLookLike(actualItem); } }
public async void SaveAttachmentAsync_Updates_Rev_On_Success() { //arrange. var entity = new SampleEntity { _rev = "old rev" }; var expectedRev = "new rev"; _db.Setup(db => db.SaveAttachmentAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <byte[]>())) .Returns(Task.FromResult(new SaveDocResponse(new CouchDBDatabase.SaveDocResponseDTO { Rev = expectedRev }))); //act. await _sut.SaveAttachmentAsync(entity, "attname", new byte[] { 1, 2, 3 }); //assert. Assert.Equal(expectedRev, entity._rev); }
public void ValidationExceptionIsNotRaised2() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = 12, Names = new List <string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id, handleAsError: false); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); val.RaiseIfHasIssues(); // --- Assert: there is no exception }
public async void SaveEntityAsync_Sets_ID_And_Rev_After_Save() { //arrange. var entity = new SampleEntity(); var expectedId = "idnew"; var expectedRev = "revnew"; _db.Setup(db => db.SaveStringDocumentAsync(It.IsAny <string>(), It.IsAny <DocUpdateParams>())) .Returns(Task.FromResult(new SaveDocResponse(new CouchDBDatabase.SaveDocResponseDTO { Id = expectedId, Rev = expectedRev }))); //act. await _sut.SaveEntityAsync(entity, null); //assert. Assert.Equal(expectedId, entity._id); Assert.Equal(expectedRev, entity._rev); }
public void SampleUseRepositoryCreate() { DataBase db = new DataBase(); var rep = new Repository.Model.Repository(db); var entity = new SampleEntity() { id = 0, iValue = 1, mValue = 1m, sValue = "1" }; rep.Create(entity); Assert.Equal(1, entity.id); Assert.Equal(1, db.Samples.Count); Assert.Equal(entity, db.Samples.First()); }
public void DDDCompareUsingEqualsOperatorsAndNullOperandsTest() { //Arrange SampleEntity entityLeft = null; SampleEntity entityRight = new SampleEntity(); entityRight.GenerateNewIdentity(); //Act if (!(entityLeft == (Entity)null))//this perform ==(left,right) { Assert.Fail(); } if (!(entityRight != (Entity)null))//this perform !=(left,right) { Assert.Fail(); } if (!((Entity)null == entityLeft))//this perform ==(left,right) { Assert.Fail(); } if (!((Entity)null != entityRight))//this perform !=(left,right) { Assert.Fail(); } entityRight = null; //Act if (!(entityLeft == entityRight))//this perform ==(left,right) { Assert.Fail(); } if (entityLeft != entityRight)//this perform !=(left,right) { Assert.Fail(); } }
public async void DeleteEntityAsync_Passes_Entity_And_Batch_Flag() { //arrange. var id = "some id 123"; var rev = "some rev 123"; var entity = new SampleEntity { _id = id, _rev = rev }; var batch = true; _db.Setup(db => db.DeleteDocumentAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>())) .Returns(Task.FromResult(new SaveDocResponse(new CouchDBDatabase.SaveDocResponseDTO()))); //act. await _sut.DeleteEntityAsync(entity, batch); //assert. _db.Verify(db => db.DeleteDocumentAsync(id, rev, batch), Times.Once()); }
public void Test_Save_ExistingEntity() { // Arrange var repository = new SampleEntityRepository(); var currentEntity = new SampleEntity(1, Guid.NewGuid().ToString()); repository.ExportedListForTest.Add(currentEntity); var updatingEntity = new SampleEntity(currentEntity.Id, Guid.NewGuid().ToString()); // Act repository.Save(updatingEntity); // Assert Assert.Single(repository.ExportedListForTest); var savedEntity = repository.ExportedListForTest.SingleOrDefault(x => x.Id == updatingEntity.Id); Assert.NotNull(savedEntity); Assert.Equal(savedEntity.Name, updatingEntity.Name); }
public void SameIdentityProduceEqualsTrueTest() { //Arrange Guid id = Guid.NewGuid(); var entityLeft = new SampleEntity(); var entityRight = new SampleEntity(); entityLeft.ChangeCurrentIdentity(id); entityRight.ChangeCurrentIdentity(id); //Act bool resultOnEquals = entityLeft.Equals(entityRight); bool resultOnOperator = entityLeft == entityRight; //Assert Assert.IsTrue(resultOnEquals); Assert.IsTrue(resultOnOperator); }
public void OperationWorksAsExpected() { // --- Arrange var serv = ServiceManager.GetService <ISampleService>(); var entity = new SampleEntity { Id = 12, Names = new List <string> { "Peter", "Valerie" } }; // --- Act serv.DoOperation(entity); // --- Assert serv.BusinessExceptionVisited.ShouldBeFalse(); serv.InfrastructureExceptionVisited.ShouldBeFalse(); }
/// <summary> /// Map dynamic bus message to SampleEntity ready for storage /// </summary> /// <param name="message">The dynamic message from the bus containing the details of the item to be mapped</param> /// <returns>a SampleEntity object populated withdata from the message</returns> public static List<SampleEntity> MapMessageToEntities(dynamic message) { var newEntities = new List<SampleEntity>(); foreach (var need in message.Needs) { Guid id; try { id = need.SampleUuid; } catch (RuntimeBinderException) { id = Guid.NewGuid(); } DateTime createdDate; try { createdDate = need.CreatedDate; } catch (RuntimeBinderException) { createdDate = DateTime.Now.ToUniversalTime(); } var newEntity = new SampleEntity { Id = id.ToString(), CreatedDate = createdDate, UpdatedDate = DateTime.Now.ToUniversalTime(), NewGuidValue = need.NewGuidValue, NewStringValue = need.NewStringValue, NewIntValue = need.NewIntValue, NewDecimalValue = need.NewDecimalValue }; newEntities.Add(newEntity); } return newEntities; }
public void OperationRaisesBusinessException() { // --- Arrange var serv = ServiceManager.GetService<ISampleService>(); var entity = new SampleEntity { Id = null, Names = new List<string> { "Peter", "Valerie" } }; // --- Act try { serv.DoOperation(entity); } catch (BusinessOperationException ex) { // --- This exception is intentionally drained } // --- Assert serv.BusinessExceptionVisited.ShouldBeTrue(); serv.InfrastructureExceptionVisited.ShouldBeFalse(); }
public void UpdateTest() { var sampleEntityDao = Container.Resolve<SampleEntityDao>(); var sampleEntity = new SampleEntity() { StringProperty = "1" }; sampleEntityDao.Insert(sampleEntity); // Modify Value: sampleEntity.StringProperty = "2"; // Update it: sampleEntityDao.Update(sampleEntity); // Check if Entity in DB was updated too: Assert.AreEqual("2", sampleEntityDao.Get(sampleEntity.Id).StringProperty); }
public void MappedQuery_FirstOrDefault_Null() { var query = new SampleEntity[0] .AsQueryable().AsMappedQuery( new DelegatedMapper<SampleEntity, SampleDto>(t => new SampleDto { Property1 = t.Property1, Property2 = t.Property2 })); query.FirstOrDefault().Should().Be(null); }
public void ValidatorWorksAsExpected6() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = null, Names = new List<string> { "Peter", "Valerie" } }; // --- Act val.Require(entity.Id.HasValue, (SampleEntity e) => e.Id, handleAsError: false); val.Require(entity.Names.Count > 0, (SampleEntity e) => e.Names); // --- Assert val.HasError.ShouldBeFalse(); val.Notifications.Count.ShouldEqual(1); val.Notifications.FirstOrDefault(n => n.Target == "Id").ShouldNotBeNull(); }
public void ValidatorWorksAsExpected1() { // --- Arrange var val = new Validator(); var entity = new SampleEntity { Id = 12, Names = new List<string> {"Peter", "Valerie"} }; // --- Act val.Require(entity.Id.HasValue, "Id"); val.Require(entity.Names.Count > 0, "Names"); // --- Assert val.HasError.ShouldBeFalse(); }
public void DoOperation(SampleEntity entity) { // --- Check for issues Verify.NotNull(entity, "entity"); Verify.NotNull((object)entity.Id, (SampleEntity e) => e.Id); Verify.Require(entity.Id.HasValue, "Id"); Verify.Require(entity.Names.Count > 0, "Names"); Verify.RaiseWhenFailed(); // --- Generate infrastructure exception if (entity.RaiseException) throw new InvalidOperationException("Infrastructure"); }
public void OperationWorksAsExpected() { // --- Arrange var serv = ServiceManager.GetService<ISampleService>(); var entity = new SampleEntity { Id = 12, Names = new List<string> { "Peter", "Valerie" } }; // --- Act serv.DoOperation(entity); // --- Assert serv.BusinessExceptionVisited.ShouldBeFalse(); serv.InfrastructureExceptionVisited.ShouldBeFalse(); }
public void ServicePublishesMessages() { var logger = new Mock<ILogger>(); var repo = new Mock<IRepository<SampleEntity>>(); var env = new Mock<IEnvironment>(); var bus = BusFactory.CreateMessageBus(); var queue = QueueFactory.CreatQueue(bus); var exchange = ExchangeFactory.CreatExchange(bus); bus.Bind(exchange, queue, "A.*"); var publisher = new MessagePublisher(bus, logger.Object, exchange,queue); var dataOps = new DataOperations(logger.Object, publisher,repo.Object,env.Object); var filter = new MessageFilter(env.Object, logger.Object); var logicClass = new MessageRouter(logger.Object, dataOps, filter); var messageData = TestMessages.GetTestCreateSampleEntityMessage(); env.Setup(e => e.GetServiceName()).Returns("Fake-Service"); env.Setup(e => e.GetServiceVersion()).Returns(2); var newEntities = new List<SampleEntity>(); var entity = new SampleEntity { UpdatedDate = DateTime.UtcNow, CreatedDate = DateTime.UtcNow, Id = Guid.NewGuid().ToString(), NewDecimalValue = 1.02M, NewGuidValue = Guid.NewGuid(), NewIntValue = 3, NewStringValue = "test" }; newEntities.Add(entity); var recivedMessages = new List<dynamic>(); var consumer = bus.Consume<object>(queue, (message, info) => Task.Factory.StartNew(() => recivedMessages.Add(message) ) ); logicClass.RouteSampleMessage(messageData); System.Threading.Thread.Sleep(5000); consumer.Dispose(); Assert.IsTrue(recivedMessages.Count >= 1); }