StructureMap: How to replace object at runtime - structuremap

I am trying to inject mocked instance of ISession (NHibernate) to structure map. Currently it all wires it up in a Bootstrap method, but I want to replace the one that is injected with a mocked one. I tried EjectAllInstancesOf but it throw execption.
[TestFixtureSetUp]
public void TestFixtureSetup()
{
Bootstrapper.Bootstrap();
//TODO: need to remove already wired up types that we are mocking.
var mockSession = MockRepository.GenerateStub<ISession>();
var mockLoggerFactory = MockRepository.GenerateStub<ILoggerFactory>();
ObjectFactory.EjectAllInstancesOf<ISession>();
ObjectFactory.EjectAllInstancesOf<ILoggerFactory>();
ObjectFactory.Inject<ISession>(mockSession);
ObjectFactory.Inject<ILoggerFactory>(mockLoggerFactory);
}
Error:
System.NullReferenceException: Object reference not set to an instance
of an object. at
StructureMap.Pipeline.HttpContextLifecycle.findHttpDictionary() in
c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:
line 50 at StructureMap.Pipeline.HttpContextLifecycle.FindCache() in
c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:
line 28 at StructureMap.Pipeline.HttpContextLifecycle.EjectAll() in
c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:
line 23 at StructureMap.Pipeline.HttpLifecycleBase`2.EjectAll() in
c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpLifecycleBase.cs:
line 18 at StructureMap.InstanceFactory.EjectAllInstances() in
c:\dev\opensource\structuremap\Source\StructureMap\InstanceFactory.cs:
line 127 at StructureMap.PipelineGraph.EjectAllInstancesOf() in
c:\dev\opensource\structuremap\Source\StructureMap\PipelineGraph.cs:
line 193 at StructureMap.Container.EjectAllInstancesOf() in
c:\dev\opensource\structuremap\Source\StructureMap\Container.cs: line
393 at StructureMap.ObjectFactory.EjectAllInstancesOf() in
c:\dev\opensource\structuremap\Source\StructureMap\ObjectFactory.cs:
line 277

You are getting this exception because your plugin type (ISession) is set up in StructureMap as a HttpContext lifecycle, and there is no HttpContext in a unit test. This is probably a bug in StructureMap, it should probably throw it's own exception explaining the problem instead of hitting a NullReferenceException.
at any rate, in your unit test setup (Boostrapper), change the lifecycle of ISession to Hybrid or something besides HttpContext.

Get rid of the calls to EjectAllInstancesOf(). Calling Inject() should do what you want.

Related

Codeception injection fails using page object

I'm new to Codeception, but I'm running into an issue injecting Page Objects. The problem occurs when I add the following construct logic to my page object.
public function __construct(\AcceptanceTester $I) {
$this->tester = $I;
}
... I got this from Login Page object example here: http://codeception.com/docs/06-ReusingTestCode#PageObjects
The error I'm getting is:
[Codeception\Exception\InjectionException]
Failed to inject dependencies in instance of 'MyCest'. Failed to create instance of 'Page\Login'. Failed to create instance of 'AcceptanceTester'. Failed to create instance of 'Codeception\Scenario'. Failed to resolve dependency 'Codeception\TestCase'.
This is how I'm injecting the page in my Cest.
protected function _inject(\Page\Login $login) {
$this->login_page = $login;
}
If I remove the __construct code, the error goes away. Is this a bug in Codeception or am I doing something wrong?
This is the work-around I found...
use \AcceptanceTester;
use Page\Login as LoginPage;
class MyCest {
protected $login_page;
public function _before(AcceptanceTester $I) {
$this->login_page = new LoginPage($I);
}
}
It is expected behaviour.
Your LoginPage constructor should not have any arguments to be instantiated during DI, so your workaround is right way to initialize LoginPage instance with AcceptanceTester instance.
When you specify AcceptanceTester as LoginPage's ctor arg DI mechanism of Codeception tries resolve dependencies recursively in the following way:
LoginPage(AcceptanceTester) -> AcceptanceTester(Scenario) -> Scenario(TestCase) -> TestCase
but TestCase is abstract class so it can not be instantiated.

Debugging JSF ManagedProperty NullPointer

Using JSF 2 on JBoss AS 7
Getting the following error:
07:36:39,579 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-/172.20.91.126:12580-16)
Error Rendering View[/views/afgarendesok.xhtml]:
com.sun.faces.mgbean.ManagedBeanCreationException:
Unable to set property searchManager for managed bean afgArendeBacking
at com.sun.faces.mgbean.ManagedBeanBuilder$BakedBeanProperty.set(ManagedBeanBuilder.java:615)
The searchManager property is defined in the AfgArendeBacking class as:
#ManagedProperty(value="#{afgArendeSokManager}")
private AfgArendeSokManager searchManager;
#Override
public AfgArendeSokManager getSearchManager() {
return searchManager;
}
public void setSearchManager(AfgArendeSokManager searchManager) {
this.searchManager = searchManager;
}
The AfgArendeSokManager is a #ManagedBean that is #SessionScoped.
Two things I don't get. One is why the error shuts down all usage of JSF not just for the session producing the error. The error seems to appear after non-usage both below the default session timeout and beyond. The other odd this is that a null pointer exception at line 606 in the BakedBeanProperty has to be the one the writeMethod variable. That variable is created via the PropertyDescriptor.getWriteMethod() call. This should have bombed earlier when creating baked bean (i.e. bakeBeanProperty method).
Any ideas how to debug? The property "searchManager" is resolved correctly since we can use the JSF views normally (both the getter/setter exist).
The search manager is our session scratch pad for propagating stuff between view and request scoped backing beans.
The article explains the issue of using reflection to access methods with covariant return types (see here: https://dzone.com/articles/covariant-return-type-abyssal). The article relates to Java 6 but the background information is very useful.
The issue you're facing and that hit us just this week (using Java 1.7.0_40) is not one of EL but of the java.beans.Introspector.

Default constructors in Xamarin.Android

I am new to Android development with Xamarin.Android and I would like to understand how to have the next issue fixed.
Sometimes after restoring my Android application from background I was facing the next error:
Unable to find the default constructor on type MainMenuFragment. The MainMenuFragment is used by the application NavigationDrawerActivity to allow users to switch between different Fragments inside the app.
In order to solve it, I added a default constructor to the MainMenuFragment as described inside the next links:
Xamarin Limitations - 2.1. Missing constructors
Added a default constructor, should fix the issue.
public class MainMenuFragment : DialogFragment
{
readonly NavigationDrawerActivity navigationDrawer;
#region Constructors
public MainMenuFragment () {} // Default constructor...
public MainMenuFragment (NavigationDrawerActivity navigationDrawer, IMenuType launchMenu = null)
{
if (navigationDrawer == null)
throw new ArgumentNullException ("navigationDrawer");
this.navigationDrawer = navigationDrawer;
...
Fragment UpdateTopFragmentForCurrentMenu (Fragment newMenuRootFragment = null)
{
Fragment currentMenuRootFragment = navigationDrawer.CurrentFragment; // issued line.
But now sometime in the future, the MainMenuFragment gets initialized using its default constructor and at the first time it tries to access its navigationDrawer it throws a System.NullReferenceException:
System.NullReferenceException: Object reference not set to an instance of an object
at MainMenuFragment.UpdateTopFragmentForCurrentMenu (Android.App.Fragment) <0x00018>
at MainMenuFragment.OpenMenu (IMenuType,bool) <0x0006b>
at MainMenuFragment.OnCreate (Android.OS.Bundle) <0x00053>
at Android.App.Fragment.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) <0x0005b>
at (wrapper dynamic-method) object.3919a6ec-60c1-49fd-b101-86191363dc45 (intptr,intptr,intptr) <0x00043>
How can I have a default constructor implemented without facing this null reference exception?
You're programming like a C# developer, thats what the problem is :) I faced these same hurdles learning monodroid.
Take a look at the examples out there, in java, you'll see almost all the time they initialize using a static method like object.NewInstance() which returns object. This is how they initialize their views/receivers/fragments. At that point they populate the Arguments property and store that in the fragment. You need to remove all your constructors EXCEPT the empty ones and use arguments to pass your data around. If you try to do this using constructors and regular oo concepts you'll be in for a world of hurt. Arguments.putExtra and all those methods are there. It makes things a little verbose but once you get the hang of it you'll start creating some helper methods etc.
Once you get that sorted, you'll need to figure out if you need to recreate your fragments everytime the activity is resumed and if not, mark them as RetainInstance = true as well as get them onto a fragmentmanager which will help you retain all your state.
If you haven't built on android before it's weird and certainly not what I expected. But it's reeaaallly cool, much more awesome than I expected too. And same with Xamarin.
Great similar question: Best practice for instantiating a new Android Fragment

Calling JBoss MBean functions to get threaddump

An application is using JBoss 4.2.2, and I have found it necessary to call listThreadDump(), and I expect it is in ServerInfo.
I am thinking the jar I need to find this information is jboss-jmx.jar.
So, how do I programmatically duplicate what is done by calling something similar to http://localhost:8080/jmx-console/HtmlAdaptor?action=invokeOpByName&name=jboss.system:type=ServerInfo&methodName=listThreadDump?
This is how I have accessed the ServerInfo MBean. I'm using JBoss AS 5.1, but this method should be the same.
To call listThreadDump(), you can invoke() the method on the ServerInfo MBean using an MBeanServer instance.
Additionally, you can access attributes of MBeans using the same MBeanServer.
Sample code:
// imports
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.jboss.mx.util.MBeanServerLocator;
try {
MBeanServer server = MBeanServerLocator.locate();
ObjectName name = new ObjectName("jboss.system:type=ServerInfo");
// invoke the listThreadDump method and capture its output
String threadDumpHtml = (String) server.invoke(name, "listThreadDump", null, null);
// access a simple attribute of the ServerInfo object
String jvmName = (String) server.getAttribute(name, "JavaVMName");
} catch (Exception e) {
// Ideally catch the 3 exact exceptions
}
Finally, I find it handy when MBeans expose an 'instance' attribute, so you can then access the object directly (CastToType) server.getAttribute(name, "instance") instead of always going through the MBeanServer. For example, when using JMS, the ServerPeer instance is nice to have as you can get message counters on your queues and topic subscribers.

What does this error in calling a method mean?

I have just started out in Vala, and I tried to make a simple program that asks two inputs:
An int that specifies a cycle degree; and
A char that contains I / R for either an iterative or recursive process.
Just before compiling, I got this error:
test0.vala:8.5-8.16: error: Access to instance member `test0.test_exec' denied
test_exec(q);
^^^^^^^^^^^ //the entire statement
Compilation failed: 1 error(s), 0 warning(s)
The pastebin for the very simple program is located here.
Here's a snippet:
public static void main(string[] args)
{
stdout.printf("Greetings! How many cycles would you like? INPUT: ");
int q=0;
stdin.scanf("%d", out q);
test_exec(q);
}
public void test_exec(int q)
{
//method code here
}
Can you please enlighten me about what to do, and some tips? Thanks.
You defined test_exec as an instance (non-static) method. Unlike a static method, an instance method needs to be called on an instance of the given class. However you're trying to call it without such an instance and thus get an error.
So you either need to create an instance of the test0 class and call test_exec on that (though that would make little sense since test_exec does not depend on or change any state of the object - as a matter of fact the test0 class does not have any state) or make test_exec as well as the other methods called by test_exec static.

Resources