Asserting a method invocation on one of several injected types - rhino-mocks

We use RhinoMocks. I have a type into whose constructor 9 types are injected. I'd like a way of automocking the type, but being able to detect a particular method invocation on one of the injected objects (i.e. I only care about a single method invocation on one of the injected objects).
Is this possible, or do I have to manually inject all the mock objects into the constructor?

I haven't seen any frameworks that would auto-create these mocks for you. You can do it in your [SetUp] method, so at least the tests will not be cluttered with boilerplate code.

I need to check out http://autofixture.codeplex.com/. Its not really container specific, there is an extension for rhino mocks. Disclaimer: I haven't tried autofixture yet.

Related

AspectJ, separating native library calls from application calls

I am using AspectJ and Load-time weaving to trace methods calls in an arbitrary java program. I can trace all calls using the standard:
call(* *.*(..))
But what I now trying to do is separate out calls to the native java libraries and any application code:
nativeCalls(): !within(MethodTracer) && call(* java..*.*(..));
appCalls(): !within(MethodTracer) && call(* *.*(..)) && !call(* java..*.*(..));
The issue is that the nativeCalls() pointcut is picking out calls to application classes that inherit from native java classes, even though the signatures do not start with java.lang. or java.util, etc.
For example:
If I have a class tetris.GameComponent that inherits from java.awt.Component, my nativeCalls() pointcut will pick out tetris.GameComponent.getBackground() when the method is actually implemented in java.awt.Component.getBackground().
Is there a way to have my nativeCalls() pointcut ignore the calls to inherited methods?
I hope this is clear. I can provide additional info if necessary. Thanks for any help that can be provided.
Actually I have no idea why you want to exclude those inherited method calls from your trace because IMO it is important or at least interesting to know if a method was called on one of your classes, even if that method was defined in a JDK super class.
But anyway, the answer is no, you cannot exclude calls to JDK methods from your nativeCalls() pointcut if those calls are actually made upon target objects typed to one of your application classes. At the time the call is made, AspectJ does not know how the JVM will resolve the polymorphism. There can be several cases:
Call to Foo.aaa(), existing method Foo.aaa() is executed. This is the simple case where a called method actually exists.
Call to Foo.bbb(), inherited method Base.bbb() is executed (polymorphism). This is the case you want to exclude, but you cannot because the fact that a base method is called will only be known when the method is executed. Furthermore, if Base is a JDK class, you cannot even intercept its method executions with AspectJ.
Call to Base.ccc(), non-overridden method Base.ccc() is executed. This can happen if you directly create an instance of Base or also if you assign/cast a Foo instance to a variable typed Base, e.g. Base obj = new Foo(), and call obj.ccc() which has not been overridden by Foo.
Call to Base.ddd(), overridden method Foo.ddd() is executed (polmorphism). This also happens if you assign/cast a Foo instance to a variable typed Base, e.g. Base obj = new Foo(), and call obj.ddd() which has been overridden by Foo.
So much for not being able to easily exclude the polymorphism stuff when calling inherited JDK method.
Now the other way around: You can easily intercept execution() instead of call() upon your application classes and take advantage of the fact that JDK method executions cannot be intercepted anyway: pointcut appMethod() : execution(* *(..));

Instantiation of System.ServiceModel.Description.WsdlContractConversionContext class

For the case of a project requirement, I need to instantiate WsdlContractConversionContext which is not having a constructor for doing so.
Is there any work around to achieve this?
WsdlContractConversionContext is a member of the System.ServiceModel.Description namespace.
Note:
The requirement exactly is that, I am doing an implementation of IWsdlExportExtension.ExportContract and IWsdlImportExtension.ImportContract, and to unit test this implemetation I need the instance of WsdlContractConversionContext.
There are basically two ways to do that: you can either use reflection to call the non-public constructor of the class (making sure you're passing appropriate parameters to it); or you can let WCF create it for you, and use it wherever you need. The WsdlContractConversionContext is passed as one of the parameters to either IWsdlExportExtension.ExportContract or an IWsdlImportExtension.ImportContract, so you'd need to implement one of the two interfaces (exporting is usually easier, since you won't need to fiddle with WSDL-consuming tools), and force the interface to be called (you may need to hit the service metadata endpoint for that).
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/10/06/wcf-extensibility-wsdl-export-extension.aspx has an example of an implementation of a WSDL export extension.
Update following edit in the question: many parts of WCF are notoriously hard to be unit tested. If you can't use WCF itself to create the instance, the only alternative you have is to use reflection. To create an instance of the conversion context class you need an instance of a ContractDescription (which you can create for your contract, but isn't easy), and a PortType, which is even harder. I'm afraid that unit testing your implementation of the WSDL export / import extension may not be worth the effort.

What does Kernel.Inject(instance); actually do?

I am learning to use dependency injection with ninject. Most of the properties and methods are fairly intuitive, one that has me though is Kernel.Inject(instance);
What does the Inject method actually do as it doesn't return anything. I've looked around but search for a method called inject on a dependency injection container is a nightmare, I can't find any references to the method specifically.
Kernel.Inject(instance) will inject dependencies into an already existing object.
That's why it returns void because it takes the parameter object instance and starts to investigate it's methods and property setters looking for the [Inject] attribute. Then it will call them with the resolved instances of their parameter types. (this is called Method or Property injection)
So when contructor injection is not enoughpossible you can Kernel.Inject to fill in your dependencies for a given instance.
You can read more about this here: Ninject Injection Patterns

FxCop, compose list of callers from dependent assembly

I'm building a couple of customs FxCop rules and one of the rules needs to enforce that a constructor is called in specific methods. For that, I need to create a list of callers, to that specific constructor, prior to performing the actual test. How is this possible? Is there some kind of handle to acquire a list of all loaded assemblies in the ApplicationDomain, where I can iterate through the classes and find the constructor Method object? Ideally the list of callers should be composed in the BeforeAnalysis method.
The Microsoft.FxCop.Sdk.CallGraph.CallersFor(Method) method may give you what you want. However, the general approach you seem to be describing is rarely a good idea because it would typically assign the problems to the wrong target. For example, in the scenario you describe, it would presumably be desirable to attribute the problems to the methods that should but do not contain the target contructor call. However, if your analysis target is the constructor, the detected problems will be attributed to the constructor rather than the methods that should have called it.
I think I haven't explained the question very well, but I see your point.
I have 3 different assemblies and for certain method calls from one assembly to another, I need to ensure that a benchmark constructor invoked. The benchmark class resides in a 4th assembly. Now my problem was that only VS2010 only loads one target assembly for analysis and when I used the CallGraph to construct the a list of methods calling the constructur, it would not find any. When Invoking FxCopCmd.exe manually I could just add the dependent assemblies manually with the /file: parameter.
My solution is to load the different assemblies manually (not relying on the loaded assembly in RuleUtilities.AnalysisAssemblies and contruct the list of callers in the BeforeAnalysis method.
RuleUtilities.GetAssembly(
RuleUtilities.AnalysisAssemblies
.First().Directory + "\\" + additionalAssemblyFilename)
.Types.SelectMany(type => type.Members)
.Where(member => member.IsPublic)
.Where(CanBeCastedToMethod)
.Cast<Method>()
.SelectMany(CallGraph.CallersFor);
With this approach I can contruct a list of callers, for each of the assemblies and for the benchmark class constructor. Works perfectly i VS2010.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.