I am trying to test my ViewComponent with XUnit.
When I debug through the component and set a break point right before it returns the Component View, the model is set.
Here is the simple model I am returning.
public class IntDashMakeRecAssgnmntsPoRespMngrVM
{
public IEnumerable<Audit> Audits { get; set; }
}
And I am trying to assert the Audits.Count() is greater than 0.
Here is my View Component:
public class IntDashMakeRecAssgnmntsPoRespMngrViewComponent : ViewComponent
{
private IAuditRepository _auditRepo;
private IExternalRepository _externalRepo;
public IntDashMakeRecAssgnmntsPoRespMngrViewComponent(IAuditRepository auditRepo,
IExternalRepository externalRepo)
{
_auditRepo = auditRepo;
_externalRepo = externalRepo;
}
public IViewComponentResult Invoke()
{
ClaimsPrincipal user = HttpContext.Request.HttpContext.User;
short staffId = short.Parse(user.Claims.Single(c => c.Type == "StaffId").Value);
// Get all Internal Audits that are not closed and not completed
var audits = _auditRepo.Audits
.Include(a => a.Findings).ThenInclude(f => f.Recommendations).ThenInclude(r => r.Assignments)
.Where(a => a.StatusID != 3 && a.StatusID != 11);
var external = _externalRepo.ExternalRecords;
audits = audits.Where(a => !external.Any(e => e.AuditID == a.AuditID));
if (User.IsInRole("PAG_SPEC") && !User.IsInRole("PAG_ADMIN_INT"))
{
audits = audits.Where(a =>
a.Assignments.Any(assn => assn.AssignmentAuditId == a.AuditID
&& assn.AssignmentRoleId == 2 && assn.AssignmentStaffId == staffId));
}
// Where audit has a recommendation without an assigned PO Authorizer
// OR without an assigned Responsible Manager (Rec Level).
List<Audit> auditsToAssign = new List<Audit>();
foreach (Audit audit in audits)
{
foreach (Finding finding in audit.Findings)
{
foreach (Recommendation rec in finding.Recommendations)
{
if (!rec.Assignments.Any(asgn => asgn.AssignmentRoleId == 15)
|| !rec.Assignments.Any(asgn => asgn.AssignmentRoleId == 26)
)
{
auditsToAssign.Add(rec.Finding.Audit);
break;
}
}
}
}
IntDashMakeRecAssgnmntsPoRespMngrVM intDashMakeRecAssgnmntsPoRespMngrVM =
new IntDashMakeRecAssgnmntsPoRespMngrVM
{
Audits = auditsToAssign
};
return View("/Views/InternalAudit/Components/Dashboard/IntDashMakeRecAssgnmntsPoRespMngr/Default.cshtml", intDashMakeRecAssgnmntsPoRespMngrVM);
}
}
When I get to this line in debugging and break to inspect, I have 1 Audit which I want:
return View("/Views/InternalAudit/Components/Dashboard/IntDashMakeRecAssgnmntsPoRespMngr/Default.cshtml", intDashMakeRecAssgnmntsPoRespMngrVM);
Now here is my Unit Test:
[Fact]
public void ReturnsAudit_1Finding_1Rec_1Asgn_PONeeded_RespMnrAssigned()
{
// Arrange
var audits = new Audit[]
{
new Audit { AuditID = 1 }
};
var findings = new Finding[]
{
new Finding{ Audit = audits[0], FindingId = 1 } // 1 Finding
};
var recommendations = new List<Recommendation>()
{
new Recommendation // 1 Rec
{
Finding = findings[0],
Assignments = new List<Assignment>()
{
// PO Authorizor
new Assignment { AssignmentRoleId = 15 }
// No Responsible Manager
}
}
};
audits[0].Findings = findings;
findings[0].Recommendations = recommendations;
Mock<IAuditRepository> mockAuditRepo = new Mock<IAuditRepository>();
mockAuditRepo.Setup(m => m.Audits).Returns(audits.AsQueryable());
Mock<IExternalRepository> mockExternalRepo = new Mock<IExternalRepository>();
mockExternalRepo.Setup(m => m.ExternalRecords).Returns(
new External[0].AsQueryable()
);
// Act
var component = new IntDashMakeRecAssgnmntsPoRespMngrViewComponent(
mockAuditRepo.Object, mockExternalRepo.Object);
component.ViewComponentContext = new ViewComponentContext();
component.ViewComponentContext.ViewContext.HttpContext = TestContext;
var result =
component.Invoke() as IntDashMakeRecAssgnmntsPoRespMngrVM;
int auditCount = (result).Audits.Count();
// Assert
Assert.Equal(1, auditCount);
}
Why is result null on this line?
var result =
component.Invoke() as IntDashMakeRecAssgnmntsPoRespMngrVM;
I also tried this first and it is still null:
ViewComponentResult result =
component.Invoke() as ViewComponentResult;
int auditCount =
((IntDashMakeRecAssgnmntsPoRespMngrVM)result.Model).Audits.Count();
I figured it out.
I wasn't casting the result to the right type.
I had this:
ViewComponentResult result =
component.Invoke() as ViewComponentResult;
int auditCount =
((IntDashMakeRecAssgnmntsPoRespMngrVM)result.Model).Audits.Count();
It should be this:
var result =
component.Invoke() as ViewViewComponentResult;
int auditCount =
((IntDashMakeRecAssgnmntsPoRespMngrVM)result.ViewData.Model).Audits.Count();
ViewViewComponentResult instead of ViewComponentResult.
I have a repository with this method
public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,
IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");
I have a method that is using it as such to get a user to work on
var user = this.applicationUserRepository.Get(x => x.EmailAddress == userName).FirstOrDefault();
It then calls the same method with a different expression further in the method as follows to check the user working on the first user
var changingUser = this.applicationUserRepository.Get(x => x.Id == changingUserId).FirstOrDefault();
I am trying to mock the repository with two setups to call it twice in the same test.
string emailAddress = "myaddresss#test.com";
int changingUserId = 5;
var targetUsers = new List<ApplicationUser>
{
new ApplicationUser { Id = 1, Password = "Testing123", EmailAddress = emailAddress }
};
// Setup the user that will be modified to be found
var mockApplicationUserRepository = new Mock<IRepository<ApplicationUser>>();
mockApplicationUserRepository
.Setup(aur => aur.Get(x => x.EmailAddress == userName, null, string.Empty))
.Returns(targetUsers.AsEnumerable());
// Set up to query the changing user to not be found
mockApplicationUserRepository
.Setup(aur2 => aur2.Get(x => x.Id == changingUserId, null, string.Empty))
.Returns(new List<ApplicationUser>().AsEnumerable()); // Empty list
Even though the second call will never be hit, for this test, I want to learn how to set this up.
When I run the test the first call
var user = this.applicationUserRepository.Get(x => x.EmailAddress == userName).FirstOrDefault();
I get null
If I change the mock to have
It.IsAny<Expression<Func<ApplicationUser, bool>>>()
I get the expected user back.
I can not figure out how I will set the two calls up so it will know which expression to use. Any help will be appreciated.
The problem is that Moq does not compare the expressions you use (only reference equality).
Using this little helper class:
public static class LambdaCompare
{
public static bool Eq<TSource, TValue>(
Expression<Func<TSource, TValue>> x,
Expression<Func<TSource, TValue>> y)
{
return ExpressionsEqual(x, y, null, null);
}
public static Expression<Func<Expression<Func<TSource, TValue>>, bool>> Eq<TSource, TValue>(Expression<Func<TSource, TValue>> y)
{
return x => ExpressionsEqual(x, y, null, null);
}
private static bool ExpressionsEqual(Expression x, Expression y, LambdaExpression rootX, LambdaExpression rootY)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
var valueX = TryCalculateConstant(x);
var valueY = TryCalculateConstant(y);
if (valueX.IsDefined && valueY.IsDefined)
return ValuesEqual(valueX.Value, valueY.Value);
if (x.NodeType != y.NodeType
|| x.Type != y.Type) return false;
if (x is LambdaExpression)
{
var lx = (LambdaExpression) x;
var ly = (LambdaExpression) y;
var paramsX = lx.Parameters;
var paramsY = ly.Parameters;
return CollectionsEqual(paramsX, paramsY, lx, ly) && ExpressionsEqual(lx.Body, ly.Body, lx, ly);
}
if (x is MemberExpression)
{
var mex = (MemberExpression) x;
var mey = (MemberExpression) y;
return Equals(mex.Member, mey.Member) && ExpressionsEqual(mex.Expression, mey.Expression, rootX, rootY);
}
if (x is BinaryExpression)
{
var bx = (BinaryExpression) x;
var by = (BinaryExpression) y;
return bx.Method == #by.Method && ExpressionsEqual(bx.Left, #by.Left, rootX, rootY) &&
ExpressionsEqual(bx.Right, #by.Right, rootX, rootY);
}
if (x is ParameterExpression)
{
var px = (ParameterExpression) x;
var py = (ParameterExpression) y;
return rootX.Parameters.IndexOf(px) == rootY.Parameters.IndexOf(py);
}
if (x is MethodCallExpression)
{
var cx = (MethodCallExpression)x;
var cy = (MethodCallExpression)y;
return cx.Method == cy.Method
&& ExpressionsEqual(cx.Object, cy.Object, rootX, rootY)
&& CollectionsEqual(cx.Arguments, cy.Arguments, rootX, rootY);
}
throw new NotImplementedException(x.ToString());
}
private static bool ValuesEqual(object x, object y)
{
if (ReferenceEquals(x, y))
return true;
if (x is ICollection && y is ICollection)
return CollectionsEqual((ICollection) x, (ICollection) y);
return Equals(x, y);
}
private static ConstantValue TryCalculateConstant(Expression e)
{
if (e is ConstantExpression)
return new ConstantValue(true, ((ConstantExpression) e).Value);
if (e is MemberExpression)
{
var me = (MemberExpression) e;
var parentValue = TryCalculateConstant(me.Expression);
if (parentValue.IsDefined)
{
var result =
me.Member is FieldInfo
? ((FieldInfo) me.Member).GetValue(parentValue.Value)
: ((PropertyInfo) me.Member).GetValue(parentValue.Value);
return new ConstantValue(true, result);
}
}
if (e is NewArrayExpression)
{
var ae = ((NewArrayExpression) e);
var result = ae.Expressions.Select(TryCalculateConstant);
if (result.All(i => i.IsDefined))
return new ConstantValue(true, result.Select(i => i.Value).ToArray());
}
return default(ConstantValue);
}
private static bool CollectionsEqual(IEnumerable<Expression> x, IEnumerable<Expression> y, LambdaExpression rootX, LambdaExpression rootY)
{
return x.Count() == y.Count()
&& x.Select((e, i) => new {Expr = e, Index = i})
.Join(y.Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => ExpressionsEqual(o.X, o.Y, rootX, rootY));
}
private static bool CollectionsEqual(ICollection x, ICollection y)
{
return x.Count == y.Count
&& x.Cast<object>().Select((e, i) => new { Expr = e, Index = i })
.Join(y.Cast<object>().Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => Equals(o.X, o.Y));
}
private struct ConstantValue
{
public ConstantValue(bool isDefined, object value) : this()
{
IsDefined = isDefined;
Value = value;
}
public bool IsDefined { get; private set; }
public object Value { get; private set; }
}
}
you can setup your mock like this:
Expression<Func<ApplicationUser, bool>> expr = x => x.EmailAddress == emailAddress;
var mockApplicationUserRepository = new Mock<IRepository<ApplicationUser>>();
mockApplicationUserRepository
.Setup(aur => aur.Get(It.Is<Expression<Func<ApplicationUser, bool>>>(x => LambdaCompare.Eq(x, expr)), null, string.Empty))
.Returns(targetUsers.AsEnumerable());
Just adding a comment to this old answer (though quite useful code)
This version of LambdaCompare class is missing a case to compare an UnaryExpression, something which is included in the code in the original post.
Use that code instead of this (I learnt the hard way...)
They work perfectly as console application. This is what I do:
private static int Main()
{
string databaseName = null;
string databaseUser = null;
string databasePwd = null;
string port = null;
string logDirectory = null;
string strLogLevel = null;
var exitCode = HostFactory.Run(configurator =>
{
configurator.AddCommandLineDefinition("dbname", d => { databaseName = d; });
configurator.AddCommandLineDefinition("dbuser", d => { databaseUser = d; });
configurator.AddCommandLineDefinition("dbpassword", d => { databasePwd = d; });
configurator.AddCommandLineDefinition("port", p => { port = p; });
configurator.AddCommandLineDefinition("logdirectory", l => { logDirectory = l; });
configurator.AddCommandLineDefinition("loglevel", l => { strLogLevel = l; });
configurator.ApplyCommandLine();
int intPort = 7909;
if (port != null)
intPort = Convert.ToInt32(port);
SystemDataApplication.LogLevel logLevel = SystemDataApplication.LogLevel.Info;
if (strLogLevel != null)
logLevel = (SystemDataApplication.LogLevel)Convert.ToInt32(strLogLevel);
configurator.Service<SystemDataApplication>(service =>
{
service.ConstructUsing(() => new SystemDataApplication(databaseName, databaseUser, databasePwd, intPort, logDirectory, logLevel));
service.WhenStarted(a => a.Start());
service.WhenStopped(a => a.Stop());
});
configurator.SetDescription("An application to fetch system data.");
configurator.SetDisplayName("System Data Service");
configurator.SetServiceName("SystemDataService");
configurator.RunAsNetworkService();
});
return (int)exitCode;
}
As console application it is printed in trace-log that all these are ok. If I install it (all custom arguments in command) and start it (all custom arguments in command) from command line they are empty in trace-log.
As I asked this question in a stupid way, the correct answer can be only that it is not supported in Topshelf.
I am trying to create parent child relationships using NEST client for C#. Here is the code I have. I am using elasticsearch 1.1.1 and this code seems to be adding the testp1 object to the testparent index but it is not adding any objects to the testchild index. If I do not pass a parent using the index parameters it seems to work fine. Any help regarding this is appreciated.
private static void LoadTestData()
{
var esClient = CreateNESTConnection();
esClient.MapFluent<testparent>(x => x
.IndexName("testdb")
.TypeName("testparent")
.IdField(y => y.SetPath("Id"))
.Properties(cprops => cprops
.String(a => a.Name("id"))
.Number(a => a.Name("parentid").Type(NumberType.#long))
.Number(a => a.Name("prop1").Type(NumberType.#long))
.Number(a => a.Name("prop2").Type(NumberType.#long))
.Boolean(a => a.Name("checkflag"))
));
esClient.MapFluent<testchild>(x => x
.IndexName("testdb")
.TypeName("testchild")
.SetParent("testparent")
.Properties(cprops => cprops
.Number(a => a.Name("dockey").Type(NumberType.#long))
.Number(a => a.Name("docvalue").Type(NumberType.#float))
));
testparent testp1 = new testparent();
testp1.checkflag = true;
testp1.id = "7";
testp1.parentid = 77;
testp1.prop1 = 1;
testp1.prop2 = 2;
testchild testc1 = new testchild();
testc1.dockey = 100;
testc1.docvalue = 111;
testchild testc2 = new testchild();
testc2.dockey = 100;
testc2.docvalue = 111;
esClient.Index(testp1, "testdb");
IndexParameters parameters = new IndexParameters();
parameters.Parent = "7";
var t = esClient.Index(testc1, "testdb", parameters);
Console.WriteLine(t.OK);
t = esClient.Index(testc2, "testdb", parameters);
Console.WriteLine(t.OK);
}
I have an action that updates the database based on a Jquery Droppable/Sortable. The first AJAX post works fine, but the second one gives me the error:
New transaction is not allowed because there are other
threads running in the session.
It's being posted to 2 separate actions on the same controller, using the same UnitOfWork in the controller. Not sure what I have to do to fix this.
EDIT: these are the two service methods being called:
public void NavItemSort(List<string> orderArray, string navID, string subNavID)
{
var newOrderArray = orderArray.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
var orderArrayIDs = newOrderArray.Select(x => x.Replace("ContentItem", "")).ToList();
var itemToBeSorted = Convert.ToInt32(orderArrayIDs.FirstOrDefault());
var itemContext = cmsUnitOfWork.NavigationItems.Find().Where(x => x.ID == itemToBeSorted).ToList().FirstOrDefault();
var currentSortOrder = cmsUnitOfWork.NavigationItems.Find()
.Where(x => x.NavID == itemContext.NavID &&
(itemContext.ParentID == null) ? x.ParentID == null :
x.ParentID == itemContext.ParentID).ToList();
var existingItems = currentSortOrder.Select(x => x.ID).ToList();
List<string> existingItemsString = existingItems.ConvertAll<string>(x => x.ToString()).ToList();
var newNavItemID = existingItemsString.Except(orderArray).FirstOrDefault();
var currentSortOrderExcept = currentSortOrder.Where(x => x.ID != Convert.ToInt32(newNavItemID));
foreach (var x in currentSortOrderExcept)
{
int sortOrderInt = orderArrayIDs.IndexOf(orderArrayIDs.Where(z => int.Parse(z) == x.ID).ToList().FirstOrDefault()) + 1;
NavigationItem navigationItem = new NavigationItem()
{
HasChild = x.HasChild,
Level = x.Level,
NavID = x.NavID,
ID = x.ID,
ParentID = x.ParentID,
PageID = x.PageID,
URL = x.URL,
Title = x.Title,
SortOrder = sortOrderInt,
};
if (navigationItem.SortOrder != null && navigationItem.SortOrder != 0)
{
cmsUnitOfWork.NavigationItems.Update(x, navigationItem);
}
}
cmsUnitOfWork.Commit();
}
public void NavItemAdd(List<string> orderArray, string NavID, string subNavID){
var newOrderArray = orderArray.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
var orderArrayIDs = newOrderArray.Select(x => x.Replace("ContentItem", "")).ToList();
NavID = NavID.Replace("nav", "");
int NavIDInt = int.Parse(NavID);
int subNavIDInt = int.Parse(subNavID);
var existingNavItems = cmsUnitOfWork.NavigationItems.Find().Where(x => x.NavID == NavIDInt && x.ParentID == subNavIDInt).ToList();
int currentSortOrder = 0;
if (existingNavItems.Count() != 0)
{
currentSortOrder = existingNavItems.Max(x => x.SortOrder);
}
var existingItems = existingNavItems.Select(x => x.ID).ToList();
List<string> existingItemsString = existingItems.ConvertAll<string>(x => x.ToString()).ToList();
var newNavItemID = orderArray.Except(existingItemsString).FirstOrDefault();
int newNavIDInt = int.Parse(newNavItemID);
var newNavItemList = cmsUnitOfWork.NavigationItems.Find().Where(x => x.ID == newNavIDInt).ToList();
var newNavItem = newNavItemList.FirstOrDefault();
var parentNav = cmsUnitOfWork.NavigationItems.Find().Where(x => x.ID == subNavIDInt).ToList().FirstOrDefault();
NavigationItem navigationItemUpdated = new NavigationItem()
{
ID = newNavItem.ID,
Level = 2,
NavID = NavIDInt,
PageID = newNavItem.PageID,
Title = newNavItem.Title,
URL = newNavItem.URL,
ParentID = subNavIDInt,
SortOrder = currentSortOrder + 1
};
cmsUnitOfWork.NavigationItems.Update(newNavItem, navigationItemUpdated);
cmsUnitOfWork.Commit();
}
I'm guessing you started a transaction against that context and you never dispose of it not commit it. Just a guess though as you didn't Los any code (please post code)
Maybe you have declared cmsUnitOfWork as static variable? Context must be created and destroyed on each request