Unit testing with generics - visual-studio-2010

I have something like:
class BackupList : List<Backup> {}
and the tests that VS2010 has generated for me look somewhat like:
[TestMethod()]
[DeploymentItem("[...].exe")]
public void AddBackupNormal()
{
SqlServer_Accessor.BackupList ls = new SqlServer_Accessor.BackupList("", "");
SqlServer_Accessor.Backup bk = new SqlServer_Accessor.Backup();
ls.Add(bk);
Assert.IsTrue(ls.Count == 0); // won't compile
List<SqlServer_Accessor.Backup> x = new List<SqlServer_Accessor.Backup>();
Assert.IsTrue(x.Count == 1); // compiles fine
}
however, in the above, the .Count reference fails to compile with:
Error 1 'xxx.SqlServer_Accessor.BackupList'
does not contain a definition for 'Count' and no extension method
'Count' accepting a first argument of type
'xxx.SqlServer_Accessor.BackupList'
could be found (are you missing a using directive or an assembly
reference?) C:[...]Tests\SqlServer_BackupListTest.cs
interestingly, a reference to the original type seems to contain a .Count property as I would expect... so the issue is that the _accessor seems to be casting to something other than a List<>.
how does one approach this?
TIA - e!

My first guess would be that your test class needs a reference...
using System.Collections.Generic;

Related

OMNET++ how to access function or variables in another class

I have modified inet NodeStatus.cc with a customized function that return the variable value as follows:
int NodeStatus::getValueA()
{
return ValueA;
}
Then, I created another simple module called simpleNodeB.cc and I wanted to retrieve ValueA from NodeStatus.cc. I tried the following code in simpleNodeB.cc but didn't work:
if(getParentModule()->getSubModule(NodeStatus).getValueA()==test1)
bubble("Value is the same");
The error message I got -> error: expected expected primary-expression before ')' token. I'm not sure if I used the correct way to call getValueA() function. Please enlighten me. thanks a lot.
There are many errors in your code.
The method getSubmodule requires a name of module, not a name of class. Look at your NED file and check the actual name of this module.
getSubmodule returns a pointer to the cModule object. It has to be manually cast into another class.
Assuming that an NodeStatus module in your NED is named fooStatus the correct code should look like:
cModule *mod = getParentModule()->getSubmodule("fooStatus");
NodeStatus *status = check_and_cast<NodeStatus*>(mod);
if(status->getValueA() == test1)
bubble("Value is the same");
Reference: OMNeT++ Manual.

cannot find symbol (doesn't recognize methods inside GregorianCalendar)

Issue:
CalendarTest.java:9: error: cannot find symbol
int today = d.get(Calendar.DAY_OF_MONTH);
^
symbol: method get(int)
location: variable d of type GregorianCalendar
My code:
import java.util.*;
public class CalendarTest
{
public static void main(String[] args)
{
GregorianCalendar d = new GregorianCalendar();
int today = d.get(Calendar.DAY_OF_MONTH);
}
}
So, what I've done so far was checking the API (methods get and set won't work at all).
I've also been searching stackoverflow and google to get some help about the issue, but without any positive results.
Tried switching between Java 6 and Java 7 without any result at all.
Been doing this for Calendar instead of GregorianCalendar, but the problem still remains.
I'm operating on Ubuntu 12.04. I've no clue what's wrong since those methods are included in GregorianCalendar class (as far as API says so)
Also,
CalendarTest.java:8: error: constructor GregorianCalendar in class GregorianCalendar cannot be applied to given types;
GregorianCalendar asd = new GregorianCalendar(2000, 10, 25);
^
required: no arguments
found: int,int,int
reason: actual and formal argument lists differ in length
won't work as well. It says that parameters (int, int, int) are wrong. Well it shouldn't, should it?
Please help me get past this, since I can not move any further (doing Core JAVA 2 Basics)
The code you've posted is fine. I strongly suspect you've got another class called GregorianCalendar on your classpath. I suggest you look for it and remove it. Note that Calendar.DAY_OF_MONTH itself appears to be found correctly.
One thing you might want to try (just to see which package is at fault) is explicitly specifying the types:
java.util.GregorianCalendar d = new java.util.GregorianCalendar();
int today = d.get(java.util.Calendar.DAY_OF_MONTH);
I suspect that will work, in which case you should look for a GregorianCalendar type in the default package.
If that's still not working, it suggests your Java installation is broken.

Is there a way to get the integer value of an enum in visual studio while the program is not running?

I have several large enums that are used like
switch(someEnumValue)
{
case SomeEnum.Value1:
DoSomething();
break;
case SomeEnum.Value2:
DoSomethingElse();
break;
...
case someEnum.ValueBigNumber:
break;
}
Is there a way in Visual Studio 2010 for me to see what the integer value of someEnum.SomeValue is without actually running the program and without manually counting the values in the enum definition?
Today I was finding a solution for this problem.
I couldn't find a cool solution like visual studio extension.
Instead, I found a useful trick for this problem using template code!
template<bool, int> class Value_of_someEnumValue_is;
template<> class Value_of_someEnumValue_is<false, someEnumValue> {};
Value_of_someEnumValue_is<true, someEnumValue> i;
If you compile this code, you will see the integer value of 'someEnumValue' in the error message. :)
There is nothing built in for this, though you can define the enumerations with the actual integer values directly, so one look at the enum declaration will tell you the members value:
public enum SomeEnum
{
Value1 = 0,
Value2 = 1,
...
ValueN = 78897
}
Its not clear why you want to do this, but thinking out the box; copy the enum definition into excel and see row number or copy into a new text file in visual studio and check the line number of the cursor (think its bottom right of the ide). Selecting the values from the first may even give you a selected lines count.

Code Analysis AssemblyNode.GetType always returns null

I am writing custom Code Analysis rules for Visual Studio 2010 (basically FxCop but the newest version). I am trying to get an attribute (or, a collection of all the attributes) applied to the assembly being checked, using code like the following:
public override ProblemCollection Check( ModuleNode module )
{
AssemblyNode assembly = module as AssemblyNode;
if ( assembly != null )
{
Identifier ns = Identifier.For( "System.Reflection" );
Identifier attr = Identifier.For( "AssemblyCopyrightAttribute" );
TypeNode type = assembly.GetType( ns, attr );
...
...but 'type' is always null, even when I know for fact that such an attribute is defined for the assembly.
Furthermore... when I debug this, I see that the assembly.ModuleAttributes collection is empty, as is ExportedTypes, as is Modules... it looks as though the assembly contains nothing at all! However, the 'base' ModuleNode is fully populated, and for example does contain 14 Attributes in its attribute collection.
It's as though "module as AssemblyNode" is wrong, but if so it would return null! Can anyone explain what I am doing wrong?
ModuleNodel.GetType looks for definition of the type, not use of the type. AssemblyCopyrightAttribute is defined in the mscorlib assembly, which is probably not what your rule is targeting. To find uses of AssemblyCopyrightAttribute, try using assembly.GetAttribute instead. For an example, see FxCop: custom rule for checking assembly info values.

Passing primitives to an OCMock's stub

I'm learning how to use OCMock to test my iPhone's project and I have this scenario: a HeightMap class with a getHeightAtX:andY: method, and a Render class using HeightMap. I'm trying to unit test Render using some HeightMap mocks. This works:
id mock = [OCMockObject mockForClass:[Chunk class]];
int h = 0;
[[[mock stub] andReturnValue:OCMOCK_VALUE(h)] getHeightAtX:0 andY:0];
Of course, works only for x=0 and y=0. I want to test using a "flat" height map. This means I need to do something like this:
id chunk = [OCMockObject mockForClass:[Chunk class]];
int h = 0;
[[[chunk stub] andReturnValue:OCMOCK_VALUE(h)] getHeightAtX:[OCMArg any] andY:[OCMArg any]];
But this raises two compilation warnings:
warning: passing argument 1 of 'getHeightAtX:andY:' makes integer from pointer without a cast
and a runtime error:
unexpected method invoked: 'getHeightAtX:0 andY:0 stubbed: getHeightAtX:15545040 andY:15545024'
What am I missing? I found no way to pass a anyValue to this mock.
It's been awhile since this question has been asked but I ran into this issue myself and couldn't find a solution anywhere. OCMock now supports ignoringNonObjectArgs so an example of an expect would be
[[[mockObject expect] ignoringNonObjectArgs] someMethodWithPrimitiveArgument:5];
the 5 doesn't actually do anything, just a filler value
OCMock doesn't currently support loose matching of primitive arguments. There's a discussion about potential changes to support this on the OCMock forums, though it seems to have stalled.
The only solution I've found is to structure my tests in such a way that I know the primitive values that will be passed in, though it's far from ideal.
Use OCMockito instead.
It supports primitive argument matching.
For instance, in your case:
id chunk = mock([Chunk class]);
[[given([chunk getHeightAtX:0]) withMatcher:anything() forArgument:0] willReturnInt:0];
In addition to Andrew Park answer you could make it a little bit more general and nice looking:
#define OCMStubIgnoringNonObjectArgs(invocation) \
({ \
_OCMSilenceWarnings( \
[OCMMacroState beginStubMacro]; \
[[[OCMMacroState globalState] recorder] ignoringNonObjectArgs]; \
invocation; \
[OCMMacroState endStubMacro]; \
); \
})
The you can use it like that:
OCMStubIgnoringNonObjectArgs(someMethodParam:0 param2:0).andDo(someBlock)
You can do the same for expecting. This case is for stubbing as topic starter request. It was tested with OCMock 3.1.1.
You could do like this:
id chunk = OCMClassMock([Chunk class])
OCMStub([chunk ignoringNonObjectArgs] getHeightAtX:0 andY:0]])
Readmore at: http://ocmock.org/reference/#argument-constraints
Despite being fairly hacky, the approach of using expectations to store the passed block to call later in the test code has worked for me:
- (void)testVerifyPrimitiveBlockArgument
{
// mock object that would call the block in production
id mockOtherObject = OCMClassMock([OtherObject class]);
// pass the block calling object to the test object
Object *objectUnderTest = [[Object new] initWithOtherObject:mockOtherObject];
// store the block when the method is called to use later
__block void (^completionBlock)(NSUInteger value) = nil;
OCMExpect([mockOtherObject doSomethingWithCompletion:[OCMArg checkWithBlock:^BOOL(id value) { completionBlock = value; return YES; }]]);
// call the method that's being tested
[objectUnderTest doThingThatCallsBlockOnOtherObject];
// once the expected method has been called from `doThingThatCallsBlockOnOtherObject`, continue
OCMVerifyAllWithDelay(mockOtherObject, 0.5);
// simulate callback from mockOtherObject with primitive value, can be done on the main or background queue
completionBlock(45);
}

Resources