Moq - Using MockRepository.Verify() With Times - moq

I'm looking to see if it's at all possible to specify a Times enum value in the setup of a mocked property that can then be exercised by the MockRepository.Verify() method at the Assert block of my AAA-style test. My current code reads like so:
// Arrange
var repository = new MockRepository(MockBehavior.Default);
var mockLogin = repository.Create<Login>();
mockLogin.SetupProperty(d => d.LoginID, 1515254);
var mockIApplicationEventLogService = repository.Create<IApplicationEventLogService>();
mockIApplicationEventLogService.Setup(d => d.InsertApplicationEventLog(It.IsAny<ApplicationEventLog>())).Verifiable();
var mockILoginResetFailedService = repository.Create<ILoginResetFailedService>();
mockILoginResetFailedService.Setup(d => d.GetLoginResetFailedByLoginID(It.IsAny<int>())).Returns((LoginResetFailed)null);
var mockApplicationEventLog = repository.Create<ApplicationEventLog>();
mockApplicationEventLog.SetupAllProperties();
var LoginWorkflowService = new LoginWorkflowService()
{
ApplicationEventLogService = mockIApplicationEventLogService.Object,
ApplicationEventLog = mockApplicationEventLog.Object,
LoginResetFailedService = mockILoginResetFailedService.Object
};
// Act
var result = LoginWorkflowService.CheckLoginResetFailuresLock(mockLogin.Object, It.IsAny<Guid>(), It.IsAny<SecurityPolicy_Aggregate>(), It.IsAny<string>(), It.IsAny<string>());
// Assert
result.Should().BeTrue();
mockIApplicationEventLogService.Verify(d => d.InsertApplicationEventLog(It.IsAny<ApplicationEventLog>()), Times.Never);
What I'd like to be able to do is call repository.Verify() at the end, but with my current code the Verify() call will expect InsertApplicationEventLog to have been called when in fact I expect it to never have been called. I have tried passing Times.Never into the Setup method for mockIApplicationEventLogService but it doesn't seem that there's a method override that takes it. Am I limited to individual Verify() calls if I have mocks in my repository that should never be called, or is there a way around this?

It appears as Nkosi said, it's not currently possible to do this. There is a request for this at the following URL:
https://github.com/moq/moq4/issues/373

Related

AFRAME: Event on completion of dynamic adding of component

My use-case is as follows:
In a loop, entities are being created and components are being set up. This is via a json-object that is being passed to the function. The question I have is how best to get an event that the whole set of entities and their components are being initialised. The code is something like this
var parent = document.querySelector('#parent');
var ent = document.createElement('a-entity');
parent.appendChild(ent);
for(var i =0; i = components.length; i++) {
var arr = components[i];
var cl = arr[0]; // class name
var attr = arr[2]; // component name
var attrV = arr[3]; // component data
ent.setAttribute('class', cl);
AFRAME.utils.entity.setComponentProperty(ent, attr, attrV);
//ent.setAttribute(attr, attrV); tried with this too
}
console.log('loop completed')
The loop completed gets logged before the completion of the loading of some of the components. I would like to have some sort of a call back to know that all the components have been completed loaded.
There seems to be an event componentinitialized but it sends a return for only 1 component. My real requirement (not reflected in above code) is that an entity can have multiple components added.
To use the above, I may have to set this event for every component and keep track of whether it has been completed or not. Just wondering if there is a more elegant way to do it. Thanks
Entities emit the "loaded" event. It should be easier than listening for each component initialization within the entity.
Try out:
entity.addEventListener("loaded", (e) => {
console.log(e)
})
like i did here.

Select option value - selectedchoice is not working

I am binding a SELECT HTML tag with some dynamic values using knockout JS. Additionally, i am trying to set a selected choice which is failing. Please suggest where i am going wrong.
self.level1Choices.selectedChoice = ko.observable(2); - this line does not seem to work.
The JSFiddle for this code is at http://jsfiddle.net/oarp7gwj/7/
The dropdown is not loading in the JSFiddle for some reason. I dont think i have referenced the knockout JS correctly. In my local environment, I am able to load the select box with the values. However, i am not able to set the selected value.
#Wayne Ellery, #QBM5 - please advise since you know about this already :)
You should use var to declare your model object to avoid scoping issues
var viewModel = new DataModel();
The main issue was you need to add to the Datamodel by exposing it through the this variable in the Datamodel.
var DataModel = function (client) {
var self = this;
self.level1Choices = ko.observableArray();
};
Take a look at the Helo World example as to how to do this:
http://knockoutjs.com/examples/helloWorld.html
I've scoped this to self as it's a best practice to not worry about this referring to something else mentioned here: http://knockoutjs.com/documentation/computedObservables.html.
I moved the loadAllApprovers method inside the DataModel as this is where it belongs and so that it has access to populate the datamodel.
I added the mobile services client to the constructor so that it can be mocked for testing your model.
var DataModel = function (client) {
var self = this;
self.level1Choices = ko.observableArray();
var loadAllApprovers = function () {
var allAppprovers = client.getTable('TABLE');
var query = allAppprovers.select("ID", "FirstName").read().done(function (approverResults) {
self.level1Choices(approverResults);
}, function (err) {
console.log("Error: " + err);
});
};
loadAllApprovers();
};
You were also missing knockout in your jsfiddle.
http://jsfiddle.net/az4rox0q/6/

Moq Example using out and ref needed

I am trying to build a test against some legacy method that implement out parameters.
Could you give me an example how to do this?
Just assign the out or ref parameter from the test.
Given this interface:
public interface ILegacy
{
bool Foo(out string bar);
}
You can write a test like this:
[TestMethod]
public void Test13()
{
string bar = "ploeh";
var legacyStub = new Mock<ILegacy>();
legacyStub.Setup(l => l.Foo(out bar))
.Returns(true);
Assert.IsTrue(legacyStub.Object.Foo(out bar));
Assert.AreEqual("ploeh", bar);
}
Anything wrong with the second example at the top of https://github.com/moq/moq4/wiki/Quickstart ? You really should be giving examples of what you're trying to do if you're not going to look for things like this.
Incidentally if you want to use moq (currently) to mock the out parameter too you'll also have to do the following hoop jump. Lets say that you wanted to mock an out parameter that returned another mocked object e.g.
var mockServiceA = new Mock<IMyService>();
var mockServiceOutput = new Mock<IMyServiceOutput>();
// This will not work...
mockServiceA.Setup(svc => svc.DoSomething(out mockServiceOutput.Object));
// To have this work you have to do the following
IMyServiceOutput castOutput = mockServiceOutput.Object;
mockServiceA.Setup(svc => svc.DoSomething(out castOutput));

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor) and another like this=>InsertJCDC(fakeBox).
When I stub out the parent I want to return fakePor. But when I run the code it returns null instead. Here is the unit test.
[Test]
public void PorBLL_InsertByPorInsertCV_DoingGoodCase()
{
// Startup object mapper
_Bootstrapper.Bootstrap();
// create the mock for generic Crud
IGenericCrud mockGenericCrud = MockRepository.GenerateMock<IGenericCrud>();
PorInsertCV fakePor = new PorInsertCV();
PorBoxInsertCV fakeBox = new PorBoxInsertCV();
// build fake return
PorEO fakePorNewRow = new PorEO();
fakePorNewRow.PorId = 22;
// stub parent and child insert routines.
mockGenericCrud.Stub(c => c.InsertJCDC<PorEO, PorInsertCV>(fakePor)).Return(fakePorNewRow);
mockGenericCrud.Stub(c => c.InsertJCDC<PorBoxEO, PorBoxInsertCV>(fakeBox)).Return(null);
ObjectFactory.Inject(typeof(IGenericCrud), mockGenericCrud);
IPorBLL localWithMock = ObjectFactory.GetInstance<IPorBLL>();
// build user args to csll bll with and use for insert
PorInsertCV userArgs = new PorInsertCV();
userArgs.AccessionNbr = "364-80-0007";
userArgs.NbrBoxes = 11;
userArgs.RegId = 20;
userArgs.TransmitedDt = Convert.ToDateTime("1/30/1980");
// call the bll using the stub
localWithMock.InsertByPorInsertCV(userArgs);
}
Any help is greatly appreciated
I can't really follow your code that well, but I'll give it a shot.
From my skills of deduction, this line here is the one giving you issues:
mockGenericCrud.Stub(c => c.InsertJCDC<PorEO, PorInsertCV>(fakePor)).Return(fakePorNewRow);
Because you're expecting fakePorNewRow to be returned when you call localWithMock.InsertByPorInsertCV(userArgs); - yeah?
If that's your case, what your problem is, is that it will only return fakePorNewRow when it is given fakePor ... not userArgs as you have given it.
Tell me if I'm completely off track.
HTHs,
Charles
Ps. You might want to add the tag of which mocking framework you are using to the question.

Specifying multiple parameters of the same name using HTTPService

Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:
http://foo.com?x[]=1&x[]=5&x[]=bar
This would get converted into the following array:
['1','5','bar']
Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter? For example, It would be nice to do something like the following:
var s:HTTPService = new HTTPService();
s.request['x[]'] = 1;
s.request['x[]'] = 5;
s.request['x[]'] = 'bar';
However, that will simply overwrite each value, resulting in only the last value being sent. Anyone have a better idea? I know I could just append stuff to the query string, but I'd like to do it in the POST body.
I was working on this same problem as well. Fortunatly, Flex supports this out of the box.
Just use an Array for the field value:
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;
var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
The HTTPService will convert this t0 the url parameters:
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service
I usually do something like this...
var s:HTTPService = new HTTPService();
s.url = "http://foo.com";
s.method = "post";
// add listeners...
s.addEventListenser(ResultEvent.RESULT,function(event:ResultEvent){
mx.controls.Alert.show(event.result.toString());
});
// send the data...
s.send({
a: 1,
b: 5,
c: "bar"
});
which would result in the HTTP Get / POST of:
http://foo.com?a=1&b=5&c=bar
You could also just create an associative array and pass it to the HTTPService send method, that would be something like:
var postdata:Object = {};
postdata["a"] = 1;
postdata["b"] = 5;
postdata["c"] = "bar";
// s is the HTTPService from above...
s.send(postdata);
You mentioned that All POST parameters must have the same name.
Elements that have the same name will overwrite each other in an associative array.
However, I have dealt with calendar cells before, and all 31 cells belong to the Date category.
What I did was:
var params:Object = new Object;
for (var i:uint=0; i<31; i++){
params["Date"+(jj.toString())] = date[i];
}
HTTPService....etc.
HTTPService.send(params);
So, on the POST receiving side, it would be interpreted as Date0...Date31.
Don't know if this was what you wanted, and the post was so long ago.
Come to think about it.
Why don't you do an array push of all of the elements under the same index name?
However, this means you are sending an array to the receiving side.
If you are POST-ing this, how will this be URL-referenced?

Resources