I want to mock the UniteofWork.FileApproveOverrideRepo.GetAllOverrideApprovals method
Everything working based on the code below just mylist is empty.
public async Task<List<FileApprovalOverrideResponse>> GetAllOverrideApprovals(int cpId)
{
var overrideApprovals = await UnitOfWork.FileApprovalOverrideRepository.Get(t => t.CPId == cpId, null, t => t.ActionedByUser.Company);
var mylist = overrideApprovals.ToList();
return MapperInstance.Map<List<FileApprovalOverrideResponse>>(mylist);
}
And here is how I mock my method :
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var mockedGenericRepoCPApproval = new Mock<IGenericAsyncRepository<FileApprovalOverride>>();
var listOfFileApprovalOverrride = new FileApprovalOverride[] {
new FileApprovalOverride()
{
FileApprovalOverrideId = 2,
FileId = 2,
CPId = 2,
ApprovalStatus = 3,
IntendedApproverType = (byte)approvType,
IsValid = true,
Reason = ""
},
new FileApprovalOverride()
{
FileApprovalOverrideId = 2,
FileId = 2,
CPId = 2,
ApprovalStatus = 3,
IntendedApproverType = (byte)approvType,
IsValid = true,
Reason = "",
}
};
var myenumerable = listOfFileApprovalOverrride;
mockedGenericRepoCPApproval.Setup(_ => _.Get(t => t.CPId == 1, null, t => t.ActionedByUser.Company)).ReturnsAsync(myenumerable);
mockedUnitOfWork.Setup(_ => _.FileApprovalOverrideRepository).Returns(mockedGenericRepoCPApproval.Object);
var cpApprovalService = new CpApprovalService(mockCPApprovalRepository.Object, new Mock<ICPRepository>().Object, new Mock<ICPService>().Object, new Mock<ICompanyRepository>().Object, new Mock<ICPLinkedCompanyService>().Object, new Mock<ICPExportService>().Object, new Mock<IEmailService>().Object, new Mock<ICPContactService>().Object, new Mock<ISystemUserRespository>().Object, new Mock<IUserManagementService>().Object, new Mock<IAuditLogService>().Object, new Mock<ISignCharterParty>().Object, new Mock<IEmailQueuer>().Object);
cpApprovalService.UnitOfWork = mockedUnitOfWork.Object;
cpApprovalService.MapperInstance = mapperInstanse;
return cpApprovalService;
I put a break point where I am creating the mock even there the myenumerable is correct and it has two members but when I run the test then the mylist is empty.
Related
I'm using the following code:
DynamoDBContextConfig config = new DynamoDBContextConfig()
{
ConsistentRead = false,
Conversion = DynamoDBEntryConversion.V2
};
using (DynamoDBContext context = new DynamoDBContext(config))
{
long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
QTrackStatus qTrackStatus = new QTrackStatus()
{
Key = "m#m.com",
EventCode = "CC",
EventDateTime = "2019-09-09 14:00:30",
EventLocation = "BFS",
EventLastUpdate = unixTimestamp
};
DynamoDBOperationConfig dynamoDBOperationConfig = new DynamoDBOperationConfig()
{
QueryFilter = new List<ScanCondition>()
{
{ new ScanCondition("EventCode", ScanOperator.NotEqual, "CC") }
},
ConditionalOperator = ConditionalOperatorValues.And
};
await context.SaveAsync(qTrackStatus, dynamoDBOperationConfig);
}
What I'm trying to do is only save the record if the EventCode is not CC. Currently it's always saving. I could retrieve the record first, do a check and then call SaveAsync if required - however I'd like to do it all in the SaveAsync call. Is this possible?
Unless I've missed something, it doesn't look like this is possible with the higher level api. I ended up re-factoring to the following:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
{
TableName = "QTrackStatus",
ReturnValues = ReturnValue.ALL_NEW,
ConditionExpression = "EventCode <> :ec",
UpdateExpression = "SET EventCode = :ec, EventDateTime = :edt, EventLocation = :el, EventLastUpdate = :elu",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{ ":ec", new AttributeValue("CC") },
{ ":edt", new AttributeValue("2019-09-09 14:00:30") },
{ ":el", new AttributeValue("BFS") },
{ ":elu", new AttributeValue() { N = ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString() } }
},
Key = new Dictionary<string, AttributeValue>()
{
{ "Key", new AttributeValue("m#m.com") }
}
};
try
{
UpdateItemResponse updateItemResponse = await client.UpdateItemAsync(updateItemRequest);
}
catch(ConditionalCheckFailedException e)
{
}
This allows me to achieve my goal.
I am trying to run or start an existing task definition within ECS but the documentation is lacking and I cant seem to find any examples online. I have hit a wall and I was wondering if anyone else has done a similar thing.
I am using the AWSSDK.ECS packages.
var request = JsonConvert.DeserializeObject<Request>(record.Sns.Message);
var task = new RunTaskRequest
{
Count = 1,
NetworkConfiguration = new NetworkConfiguration
{
AwsvpcConfiguration = new AwsVpcConfiguration
{
Subnets = new List<string>() { request.SubnetId},
SecurityGroups = new List<string>() { request.SecurityGroupId},
AssignPublicIp = AssignPublicIp.DISABLED
}
},
Cluster = request.Cluster,
LaunchType = LaunchType.FARGATE,
Overrides = new TaskOverride
{
ContainerOverrides = new List<ContainerOverride>
{
new ContainerOverride
{
Name = request.ContainerName,
Environment = request.EnvironmentVariables
.Select(kvp => new Amazon.ECS.Model.KeyValuePair()
{
Name = kvp.Key,
Value = kvp.Value
}).ToList()
}
}
},
TaskDefinition = request.TaskDefinitionUri
};
await new AmazonEcsClient().RunTaskAsync(task);
Check on your task definition. If the NetworkMode is awsvpc, then you must provide NetworkConfiguration parameter. This works for me:
var runTaskRequest = new ECSModel.RunTaskRequest
{
Cluster = "cluster-name",
Count = 1,
LaunchType = LaunchType.FARGATE,
TaskDefinition = "task-definition",
NetworkConfiguration = new ECSModel.NetworkConfiguration
{
AwsvpcConfiguration = new ECSModel.AwsVpcConfiguration
{
SecurityGroups = new List<string> { "security-group" },
Subnets = new List<string> { "subnet" }
}
},
Overrides = new ECSModel.TaskOverride
{
ContainerOverrides = new List<ECSModel.ContainerOverride>
{
new ECSModel.ContainerOverride
{
Name = "container-name",
Command = new List<string>
{
// In case if you need to pass parameters to your instance:
"parameter-one", "parameter-two", "etc"
}
}
}
}
};
await new AmazonEcsClient().RunTaskAsync(runTaskRequest);
I'm running into an issue where Moq doesn't return what I excpect using following code:
[TestMethod]
public void GetResultReturnsAResult()
{
var mockUnitOfWork = Arrange();
// Arrange
var controller = new ResultsController(mockUnitOfWork.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
// Act
var response = controller.GetResult(2);
// Assert
Assert.IsTrue(response is OkNegotiatedContentResult<Result>);
var contentResult = response as OkNegotiatedContentResult<Result>;
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
Assert.IsTrue(contentResult.Content.ID == 2);
}
[TestMethod]
public void GetResultReturnsNotFound()
{
var mockUnitOfWork = Arrange();
// Arrange
var controller = new ResultsController(mockUnitOfWork.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
// Act
var response = controller.GetResult(100);
// Assert
Assert.IsTrue(response is NotFoundResult);
var contentResult = response as NotFoundResult;
Assert.IsNotNull(contentResult);
}
private Mock<IUnitOfWork> Arrange()
{
var results = new List<Result>()
{
new Result()
{
ID = 1,
Name = "Result 1",
Modified = new DateTime(2017, 1, 1),
Created = new DateTime(2017, 1, 1),
CreatedBy = "Tester 1",
ModifiedBy = "Tester 2"
},
new Result()
{
ID = 2,
Name = "Result 2",
Modified = new DateTime(2017, 1, 2),
Created = new DateTime(2017, 1, 2),
CreatedBy = "Tester 1",
ModifiedBy = "Tester 2"
},
};
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockResultRepository = new Mock<IGenericRepository<Result>>();
mockResultRepository.Setup(x => x.Get(null, null, ""))
.Returns(results);
mockResultRepository.Setup(x => x.GetById(It.IsAny<int>()))
.Returns((int id) => GetById(results, id));
mockUnitOfWork.Setup(x => x.ResultRepository)
.Returns(mockResultRepository.Object);
return mockUnitOfWork;
}
private Result GetById(List<Result> results, int id)
{
return results.FirstOrDefault(r => r.ID == id);
}
In this case my TestMethods testing GetById both throw an exception with message: Object of type 'System.Object[]' cannot be converted to type 'System.Int32'.
When I change the mocking code to this:
mockResultRepository.Setup(x => x.Get(null, null, ""))
.Returns(results);
mockUnitOfWork.Setup(x => x.ResultRepository)
.Returns(mockResultRepository.Object);
mockUnitOfWork.Setup(x => x.ResultRepository.GetById(It.IsAny<int>()))
.Returns((int id) => GetById(results, id));
The GetById tests don't throw an exception but GetResultReturnsAResult doesn't return a result so it always fails.
Can anyone shed a light on this behaviour?
As suggested by Eugene Podskal in the comments, I was creating an MCVE (download here) and ran into the solution. He was in fact right that the solution was to be found in code that was not shared first.
The code that returned the
Object of type 'System.Object[]' cannot be converted to type 'System.Int32'
exception was correct in throwing this exception since
GetById
takes a
params object[]
as first parameter.
I have an array of days (mon, tue, etc..) that I might not want to show, so when I create a list of days, if they are already in the "hiddendays", it doesn't add them.
// This would return for example 1, 2
var hDays = account.ScheduleHiddenDays.Split(',').Select(int.Parse).ToList();
var daySunday = new ViewModels.Day()
{
Id = 0,
Name = "Sunday"
};
var dayMonday = new ViewModels.Day()
{
Id = 1,
Name = "Monday"
};
var dayTuesday = new ViewModels.Day()
{
Id = 2,
Name = "Tueday"
};
var dayWednesday = new ViewModels.Day()
{
Id = 3,
Name = "Wednesday"
};
var dayThursday = new ViewModels.Day()
{
Id = 4,
Name = "Thursday"
};
var dayFriday = new ViewModels.Day()
{
Id = 5,
Name = "Friday"
};
var daySaturday = new ViewModels.Day()
{
Id = 6,
Name = "Saturday"
};
// This is where I need to check if they exist in hDays, it doesn't add them to this list. But how?
model.ScheduleHiddenDays = new List<ViewModels.Day>()
{
daySunday,
dayMonday,
dayTuesday,
dayWednesday,
dayThursday,
dayFriday,
daySaturday
};
Something along the lines of this:
var days = new List<ViewModels.Day>()
{
daySunday,
dayMonday,
dayTuesday,
dayWednesday,
dayThursday,
dayFriday,
daySaturday
};
model.ScheduleHiddenDays = days.Where(x => !hDays.Contains(x.Id)).ToList();
public class Foo
{
public ObjectId _id { get; set; }
public BsonDocument properties { get; set; }
}
public void FindFoos()
{
var client = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
var server = client.GetServer();
var db = server.GetDatabase("FooBar");
//var collection = db.GetCollection<GeoJsonFeature<GeoJson2DGeographicCoordinates>>("Sections");
var collection = db.GetCollection<Foo>("Foos");
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo1"},
{"Bar" , "bar1"}
}
});
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo2"},
{"Bar" , "bar2"}
}
});
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
var result = collection.Find(query).First();
}
calling FindFoos results in the following exception:
Unsupported where clause: Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value.AsString == "foo1"))).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unsupported where clause: Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value.AsString == "foo1"))).
at the line:
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
I can do this query easily in the mongodb shell as:
db.Foos.find( {'properties.Foo' : 'foo1'} );
What is the correct way to do this query with Linq?
Try LINQ's SelectMany() method. It is used to flatten nested collections. Instead of using nested for loops, we can do the task in a more 'LINQ' way.
Ex given below -
Master m1 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 1, s = "C++" }, new obj { i = 1, s = "C#" }, new obj { i = 1, s = "Java" } } };
Master m2 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 4, s = "PHP" }, new obj { i = 5, s = "Ruby" }, new obj { i = 6, s = "Perl" } } };
List<Master> lstMasters = new List<Master> { m1, m2 };
var result = lstMasters.SelectMany(m => m.lstObj).Where(o => o.s == "PHP");
Just replace the Master class with your BsonDocument.