Register a method as a listener with aspectj - aop

I already know how to intercept a method execution, but in this case, I will not call the method directly, it should be called when an event is fired (Observer pattern). How can i register that method as a listener using aspectj?

AspectJ as well as the AJDT for Eclipse contain code examples, including one implementing the Observer design pattern. Go to the AspectJ documentation page, select Examples and from there download the source code archive.

Related

How to intercept JUnit5 method annotated with #Disabled?

I would like to write a JUnit5 Extension where I have to take some action when a test method annotated with #Disabled is found. Unfortunately, beforeTestExecution() is not called for such methods. Does anybody have an idea how to intercept such #Disabled test methods ?
Thanks !
As described in the User Guide, you can disable the built-in ExecutionCondition that handles #Disabled by default by setting junit.jupiter.conditions.deactivate to org.junit.*DisabledCondition (see Configuration Parameters on how to set it). This will cause your tests to be executed.
Next, you need to implement your own ExecutionCondition extension, check for #Disabled, take your action and return ConditionEvaluationResult.disabled("...").
In order to avoid having to register your extension on each test class, you can activate Automatic Extension Registration and register your extension globally.
Depending on what you want to achieve, it may be easier to register your own TestExecutionListener (see Plugging in Your Own Test Execution Listeners) and implement executionSkipped().
The extension point used here is https://github.com/junit-team/junit5/blob/master/junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExecutionCondition.java
It might be interesting to find out how several implementors compose, i.e. if the 2nd one will be called at all and under what circumstances. You’ll probably have to dive into Jupiter code or do some experiments.

Initialize mmvcross IOC for Windows Runtime Component Background Task

In building my current (first) Windows Phone app it requires me to create a Windows Runtime Component to achieve the functionality I require. In order for this setup to work and not duplicate a lot of code from my PCLs into the task class itself, I wanted to use the MMVMCross IOC that I am already using throughout the application.
Unfortunately, the Background Task (IBackgroundTask) is executed in an entirely different process. Trying to utilize the IOC via Mvx.Resolve throws a NullReferenceException. I cannot figure out how to initialize the IOC as the standard "setup.cs" method does not work in the Runtime Component.
I do not need the entire MVVMCross stack for this -- just the IOC.
Thank you.
I finally figured it out. I have to re-register on the background task, but to initialize you would call the basic initialize method on the simple IOC container:
Cirrious.CrossCore.IoC.MvxSimpleIoCContainer.Initialize();
Plugins were a problem, as the standard plugin mechanism is not available, but you can manually register the interfaces such as this:
Mvx.LazyConstructAndRegisterSingleton<IMvxFileStore>(() => new MvxWindowsCommonBlockingFileStore());
Of course, you can still register your other types and interfaces as you normally would.

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(* *(..));

Generate a Mock object with a Method which raises an event

I am working on a VB.NET project which requires the extensive used of Unit Tests but am having problems mocking on of the classes.
Here is a breakdown of the issue:
Using NUnit and Rhino Mock 3.6
VS2010 & VB.NET
I have an interface which contains a number of methods and an Event.
The class which implements that Interface raises the event when one of the methods is called.
When I mock the object in my tests I can stub methods and create/assert expectations on the methods with no problems.
How do I configure the mock object so that when a method is called the event is raised so that I can assert that is was raised?
I have found numerous posts using C# which suggest code like this
mockObject.MyEvent += null...
When I try this 'MyEvent' does not appear in Intellisense.
I'm obviously not configuring my test/mock correctly but with so few VB.NET examples out there I'm drawing a blank.
Sorry for my lack of VB syntax; I'm a C# guy. Also, I think you should be congratulated for writing tests at all, regardless of test first or test last.
I think your code needs refactoring. It sounds like you have an interface that requires implementations to contain an event, and then another class (which you're testing) depends on this interface. The code under test then executes the event when certain things happen.
The question in my mind is, "Why is it a publically exposed event?" Why not just a method that implementations can define? I suppose the event could have multiple delegates being added to it dynamically somewhere, but if that's something you really need, then the implementation should figure out how that works. You could replace the event with a pair of methods: HandleEvent([event parameters]) and AddEventListener(TheDelegateType listener). I think the meaning and usage of those should be obvious enough. If the implementation wants to use events internally, it can, but I feel like that's an implementation detail that users of the interface should not care about. All they should care about is adding their listener and that all the listeners get called. Then you can just assert that HandleEvent or AddEventListener were called. This is probably the simplest way to make this more testable.
If you really need to keep the event, then see here for information on mocking delegates. My advice would be to mock a delegate, add it to the event during set up, and then assert it was called. This might also be useful if you need to test that things are added to the event.
Also, I wouldn't rely on Intellisense too much. Mocking is done via some crafty IL code, I believe. I wouldn't count on Intellisense to keep up with members of its objects, especially when you start getting beyond normal methods.

NServiceBus: need to configure channels for my Gateway with code

I'm engaged in building NServiceBus Gateway handler, and I need to avoid config files so that all configuration is defined inside c# classes. As a result I have to convert the following section to c# code
<GatewayConfig>
<Channels>
<Channel Address="http://localhost:25899/SiteB/" ChannelType="Http" Default="true"/>
</Channels>
</GatewayConfig>
I've found GatewayConfig, ChannelCollection and ChannelConfig in a NServiceBus.Config namespace, but I can not link them together, coz GatewayConfig refers to ChannelCollection, but ChannelCollection has nothing to do with ChannelConfig. Please help
Just create a class implementing IProvideConfiguration of GatewayConfig. That gives you a way to provide your own config. Look at the pubsub sample for the exact details on how to do this.
Well, I've found the way to do it as I installed Reflector and looked into the implementation. There is a ChannelCollection.CreateNewElement() method returning back System.Configuration.ConfigurationElement. NServiceBus overriden the method instantiating ChannelConfig inside it, so all I have to do is to cast ConfigurationElement type to ChannelConfig type which is far from intuitive interface. Looks like this NServiceBus.Config.ChannelCollection is kind of unfinished work, because if you look at other collections like NServiceBus.Config.MessageEndpointMappingCollection you can find there all necessary type-safe methods to work with its child elements NServiceBus.Config.MessageEndpointMapping, so I think NServiceBus team was just lazy to make the same for ChannelCollection.
UPDATE: as CreateNewElement() method is protected, I have to implement my own class inherited from ChannelCollection to make a method adding new ChannelConfig element publicly available