Moq Example using out and ref needed - moq

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));

Related

Moq - Using MockRepository.Verify() With Times

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

Code coverage doesn't mark a line that uses <T> as passed

I don't know why i'm having this behavior with my code coverage, maybe someone knows the reasson.
As you may know, code coverage is blue when reached, red when not reached, yellow when partially reached a line of code.
I coded a little mapper that receives a IDataReader and turns into object thanks to reflection.
internal IEnumerable<T> Convert<T>(System.Data.IDataReader dataReader) where T : new()
{
var columns = this.GetColumns(dataReader); // get a list of column name... not important.
var result = new List<T>();
while (dataReader.Read())
{
var nuevoObjeto = new T(); // <-- this line is yellow in code coverage.
foreach (var item in columns)
{
var pi = nuevoObjeto.GetType().GetProperty(item);
pi.SetValue(nuevoObjeto, dataReader[columns.IndexOf(item)]);
}
result.Add(nuevoObjeto);
}
return result;
}
As you can see, the yellow line is not a conditional like IF or WHILE... is just a simple "new T"
And if you debug this code, debug reaches very well that line, in fact test is green with expected results.
Test performs this steps.
Fake IDataReader (with nSubstitute)
Only 1 result on the datareader.
T is tested with only one TestClass... like USERTEST.
hope someone knows why this happens...
thanks!
The IL that gets generated for that line is equivalent to:
T nuevoObjeto = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);
This allows structs to be used for the generic type as they satisfy the new constraint.
So, if you want 100% code coverage, test your generic method with a struct or change the constraint to require that the generic type be a class using where T : class
Try to test it also with struct or add class constraint to the generic method - http://www.codeproject.com/Tips/175592/Code-Coverage-And-Generics

Cannot implicitly convert type 'System.Linq.IQueryable to System.Data.Entity.DbSet<>

I receive the following error when I try to run my code. I haven't managed to solve it yet, please Help:
edit: Marked with * where it fails.
>
public IQueryable<Video> GetVideos([QueryString("id")] int? categorieId)
{
var _db = new TeleviziuneAcademicaAspSilverlight.Models.VideoContext();
IQueryable<Video> query = *_db.Videos;*
if (categorieId.HasValue && categorieId > 0)
{
query = query.Where(v => v.CategorieID == categorieId);
}
return query;
Change
IQueryable<Video> query =
to
IQueryable<Appname.Models.Video> query =
The reason for your error is that you have the type Video defined twice and because of using a short type name you accidentally reference not the one Video you should.
Also change it in the method's return value
public IQueryable<Appname.Models.Video> GetVideos( ... )
You seem to have two classes called Video. If you need both, you'll need to project from one to the other before your return statement:
return query.Select(dbVideo => new Appname.Video()
{
Prop1 = dbVideo.Prop1,
Prop2 = dbVideo.Prop2,
// etc.
});
Though you'll probably need to change the return type to an IEnumerable<> if you do that.
If you can just work with Appname.Models.Video, change IQueryable<Video> to IQueryable<Appname.Models.Video> in the method signature and the method body.

AS3: Whats determines the order of: for..in

OK I am looping through the properties in an object like so:
private var _propsList:Object = {'Type':'product_type'
,'Kind':'product_type_sub'
,'Stone':'primary_stone'
,'Stone Color':'primary_stone_sub'
,'Metal':'metal_type'
,'Brand':'product_brand'};
for(key in _propsList)
{
val = _propsList[key];
trace(key +" = "+ val);
}
I am expecting the first trace to be Type = property_type since that is the first one defined in the array, however it is coming up random everytime. I guess this is because my keys are strings and not integers, however is there a way to specify the order it loops through them?
Thanks!!
You can't rely on for (v in someObject) ... to return things in a predictable order, no.
Depending on your specific situation, you could just use an array to hold the keys, and just iterate through that:
private var keys:Array = ["Type", "Kind", "Stone", "Stone Color", "Metal", "Brand"];
private function iterate():void
{
for each (var k:String in keys)
{
trace(_propsList[k]);
}
}
Maybe a bit obvious or non-elegant, but it'd get the job done. :)
you could hack it by classing-out your "_propsList" object creating an array inside of the newly created PropsList class that references the properties in order. At that point, you could run a FOR loop on the array and get your properties in order.
OR, you could have a function inside that new class that would return an Array of those properties. like this:
public function getProps():Array {
return [myPropertyOne, myPropertyTwo, myPropertyThree];
}
In general, I think this is a case where you shouldn't depend on a particular behavior from the framework/language you are using. This type of behavior is generally poorly documented and can change from version to version.
If you really need a specific retrieval order, I would create a wrapper class as jevinkones suggested above. Maybe there's even a utility class in the framework somewhere to accomplish this (Dictionary, etc.?)
HTH,
Karthik
I found this link that gives some background:
Subtle Change in for..in Loops for ActionScript 3
This question is actually a dup of this one.
How about using an array representation like this:
var _propsList:Array = [
['Type', 'product_type'],
['Kind', 'product_type_sub'],
['Stone', 'primary_stone'],
['Stone Color', 'primary_stone_sub'],
['Metal', 'metal_type'],
['Brand', 'product_brand']
];
for(var i in _propsList) {
var elem = _propsList[i];
var key = elem[0];
var val = elem[1]
}

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.

Resources