i had a null value error in my test class
[Test]
public void when_send_the_command_it_execute_correct_command_handler()
{
//Arrange
var commandBus = new CommandBus();
ICommand commandforsend=null;
IMetaData metaDataforsend=null;
Action<ICommand, IMetaData> fakeHandler = (fakecommand, fakemetadata) =>
{
commandforsend = fakecommand;
metaDataforsend = fakemetadata;
};
commandforsend and metaDataforsend values are still null
what can happen ? help me thank you !
You are defining an Action but you are never calling it. Your code is equivalent to a separate method that assigns the values but that you don't call so the code inside the method never runs.
If you want to execute the fakeHandler you should add the following line below the declaration:
fakeHandler(aFakeCommand, aFakeMetadata);`
As you can see, this is the same as calling a regular method. You need to supply values for both parameters (fakecommand and fakemetadata).
You can find more info in the MSDN documentation.
Since your code doesn't execute fakeHandler, this behavior is OK, because you've just declared a anonymous method without executing it.
Related
I'm trying to unit test a method where a function is called in a loop. One of the parameters supplied to the method is a List<string>, declared outside the loop, that should be updated by each call that it is passed to.
I've been trying to mock this behaviour using some examples that I found on SO that involve updating the parameter inside of a Callback(), but this hasn't worked for me as expected.
Here is a short-hand example of the problem I'm having:
Method
public async Task DoSomething() {
var strings = new List<string>();
for(i = 0; i < 2; i++) {
var response = await _responder.GetResponse(i, strings);
//method adds a new string into the collection on each call
}
}
So to test this, I would need to mock both method calls, knowing that the string collection would be empty on one and contain one element on the other...
Test
public async Task TestDoSomething() {
var strings = new List<string>();
var mock = new Mock<Responder>();
mock.Setup(x => x.GetResponse(0, strings)) //mocks first iteration of loop
.ReturnsAsync(new Response())
.Callback<int, List<string>>((number, stringCollection) => {
stringCollection = new List<string> {"addedString"}; //this is where the problem occurs
strings = stringCollection;
});
mock.Setup(x => x.GetResponse(1, strings)) //mocks second iteration of loop
.ReturnsAsync(new Response());
//...
}
So at the point where I try to update the collection of strings inside the callback, studio highlights the parameter and gives me the warning The value passed to the method is never used because it is overwritten in the method body before being read.
The test fails because the setups are not matched, and trying to debug causes the test to crash and drop out.
Can anyone point me in the right direction here? Between the warning message and the fact that all the other examples of this stuff just use Returns rather than ReturnsAsync, I would guess that it's to do with the timing of updating the parameter.
Thanks in advance!
Not sure what exactly you want to test the method call or that values added to the collection.
But if you want to test that method was called, you can use Verify function like this -
mock.Verify(mock => mock.GetResponse(It.IsAny<int>(), strings), Times.Exactly(2));
PS. You should use It.IsAny<int>() cause first param obtain index from loop SO _responder.GetResponse(0, strings) calls only once and so on.
I have two action methods inside a controller. With the help of first action method, I am fetching the required data from database and I need to get this fetched data inside the second action method. I need to achieve this without passing any parameter to the second method. I don’t know how to do this as I am new to MVC.
Method 1:
public ActionResult GetData(HttpPostedFileBase file)
{
string folderPath = Server.MapPath(ConfigurationManager.AppSettings["BackupPath"]);
List<string> invalidRecords = new List<string>();
string backupFileName = FileUpload.BackupFile(file, folderPath);
invalidRecords = File.GetDataFromDB(backupFileName);
List<DataVM> lst = serviceData.GetAllData();
return View(lst);
}
Method 2:
[HttpPost]
public JsonResult GetInvalidRecords()
{
List<string> InvalidVehicleId = InvalidRecords;
return new JsonResult { Data = InvalidRecords };
}
You can use a session variable to hold the value of your 'lst' variable in your 'GetData' action:
Session["data"] = lst
Then you can retrieve it as follows and cast it to the appropriate type:
var data = (List<DataVM>)Session["data"]
https://msdn.microsoft.com/en-us/library/ms178581.aspx
You can use TempData as well
TempData["Name of Tempdata variable "]= File.GetDataFromDB(backupFileName)
and in other action you can recieve it
var getdatafromanotherAction= TempData["Name of Tempdata variable"]
If you want to call both action methods in single call, You can use
return RedirectToAction("GetInvalidRecords") in the first method. Also, you can create a class level private variable _listdata. Set it in first method , get in second method.
If you want to keep data between the 2 calls, use Tempdata.Keep and Tempdata.Peek but you need to make sure that call for second method immediately follows first method. Tempdata works between 2 requests only unless you extend its duration by using .Keep and .Peek once more.
If these two methods are to be called few calls apart, you can use session variable to keep the data.
Alternatively, you can keep the parameter of the second method call optional. So, it won't hurt other calls of the jsonresult method. Inside the method, you can check whether parameter is empty or not.
I am Calling an ASP.NET C# Method (Web Method) Using JavaScript.
C#:
[WebMethod]
public static List<Employee> GetEmployeeList(int DeptID,out int TotalRecordsCount)
{
<Employee> obj = new List<Employee>();
//obj = Geting reocrds from Database
TotalRecordsCount = obj.Count();
return obj;
}
Javascript:
function BindList(){
var DeptID = 10;
var TotalRecordsCount = 0;
PageMethods.GetEmployeeList(DeptID,TotalRecordsCount,onsuccess);
}
Now I am getting errors, while calling above js method. Please suggest me where I done mistake.
My main aim is that, Instead of returning single list, Can I add 2 or more different lists ?
Thanks in adv.
Out methods should contain the out key word when it is called like
PageMethods.GetEmployeeList(DeptID,out TotalRecordsCount, onsuccess);
But out is not a keyword in js. So I don't know if it is possible (I would be surprised). Why not return the out parameter as part of the result. So instead of just a list, a list with another value. Another thing that is unusual in your code is that you are trying to set the out parameter before calling the method.
I have never tried using an out when calling the method in Js and its probably not very good design even if it is allowed.
Also see
Is it unusual for a web service call to have an "out" parameter?
I'm a bit new to the concept of "Action" in C# and delegate in general.
I'm trying to study how to build a custom html component in MVC, and I chose the grid component of MVCContrib to start.
To add columns, typically we do
<%= Html.Grid(Model).Columns(column =>
{
column.For(model => model.Date).Format("{0:d}");
column.For(model => model.DayAmount);
column.For(model => model.LeaveType);
})
%>
and I see the source of Columns like the following
public IGridWithOptions<T> Columns(Action<ColumnBuilder<T>> columnBuilder)
{
var builder = new ColumnBuilder<T>();
columnBuilder(builder);
foreach (var column in builder)
{
if (column.Position == null)
{
_gridModel.Columns.Add(column);
}
else
{
_gridModel.Columns.Insert(column.Position.Value, column);
}
}
return this;
}
What I'm confused of is the Action parameter In this instance, Type is CustomBuilder, so when did the "CustomBuilder" object got instantiated?
I suppose, i can rewrite the calling statement above as
Html.Grid(Model).Columns(delegate(CustomBuilder<T> column)
{
});
or a bit more explicit as
Html.Grid(Model).Columns(new Action<CustomBuilder<T>>(delegate(CustomBuilder<T> column)
{
});
);
So are we saying, when the Action was instantiated with the "new" keyword above, the param "CustomBuilder" was instantiated as well?
Lastly, in the
"public IGridWithOptions<T> Columns(Action<ColumnBuilder<T>> columnBuilder)"
function,
the first two lines are
var builder = new ColumnBuilder<T>();
columnBuilder(builder);
What do they do? Looks like it's instantiating ColumBuilder object and pass it as a parameter to Action method columBuilder. Is this where you instantiate the parameter?
Thank you all.
It's nothing to do with action concept.
The delegates is present in .net from the beginning so you should start with the first step. Should build the wall before the roof.
Delegates
Lambda Expressions
Expression trees
But you should know about generic classes and methods, extension methods...
Got it after read this excellent article.
http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expressio
while it's talking about Func, the concept applies to Action, which does not return any results.
Looks like the magic happens here
var builder = new ColumnBuilder();
columnBuilder(builder);
I obviously didn't understand the fact that delegate, is just a pointer to a function (anonymous or not). You still need to supply the parameter when calling it. (Duh!).
All cleared up now.
Thank you.
I have a failing test in NSubstitute because a parameter passed in to a substituted call does not match. Here is the relevant code that is being tested:
// Arrange
PermissionsProviderSub = Substitute.For<IPermissionsProvider>();
MenuDataProviderSub = Substitute.For<IMenuDataProvider>();
PermissionsProviderSub.GetPermissions(UserId).Returns(ExpectedUserPermissions);
MenuDataProviderSub.GetMenuData(ExpectedUserPermissions.AuthorisedPageIds).Returns(Arg.Any<IList<BusinessFocusArea>>());
var sut = new MenuViewModelFactory(MenuDataProviderSub, PermissionsProviderSub);
// Act
var result = sut.Create();
// Assert
MenuDataProviderSub.Received().GetMenuData(ExpectedUserPermissions.AuthorisedPageIds);
The problem occurs in the ExpectedUserPermissions.AuthorisedPageIds property, which looks like this:
public IEnumerable<string> AuthorisedPageIds
{
get
{
return ApplicationPagePermissions != null ?
ApplicationPagePermissions.Select(permissionSet => permissionSet.PageId) :
Enumerable.Empty<string>();
}
}
As you can see, there is a LINQ Select, which is extracting the PageId property from within the ApplicationPagePermissions collection and returning it as an IEnumerable<string>. Because the projection within that property creates a new object, the substitution does not match, as it sees the 2 objects as being different.
Can I create a callback on the parameter passed in to GetMenuData so that I can examine the value of it?
The documentation on NSubstitute callbacks only talks about examining the return value from a call, rather than a parameter passed into the call.
Typical. As soon as I post to SO, the answer presents itself. Rather than expecting a specific object when creating the substitute call, I expect any instance of type IEnumerable<string> and create a callback when checking the Received() call that actually verifies the values. The substitute call becomes this:
MenuDataProviderSub.GetMenuData(Arg.Any<IEnumerable<string>>()).Returns(Arg.Any<IList<BusinessFocusArea>>());
The Received() check becomes this:
MenuDataProviderSub.Received().GetMenuData(Arg.Is<IEnumerable<string>>(a => VerifyPageIds(ExpectedUserPermissions.AuthorisedPageIds, a)));
private static bool VerifyPageIds(IEnumerable<string> expected, IEnumerable<string> actual)
{
var expectedIds = expected.ToList();
var actualIds = actual.ToList();
return expectedIds.Count == actualIds.Count && expectedIds.All(actualIds.Contains);
}