Umbrella Exception during fire event in GWT - exception

I have a Singleton Instance and when I am Firing the event whose handler uses Singleton instance it resulting in Umbrella Exception.
The code Snippets are
#UiHandler("panelButton")
void handleClick(ClickEvent e) {
AppUtils.eventBus.addHandler(PanelClickEvent.TYPE, new PanelClickEventHandler());
AppUtils.eventBus.fireEvent(new PanelClickEvent());
}
The Handler is
public class PanelClickEventHandler implements EventHandler{
#Inject
PanelDataHandler pdh;
public void displayPanelGrid() {
System.out.print(pdh.getPanelList().size());
}
}
The error is with the lines
#Inject
PanelDataHandler pdh;
My PanelDataHandler is
#Singleton
public class PanelDataHandler {
.......
#Inject
public PanelDataHandler(){
....
}
.......
}
Is there anything which I am missing?
shouln't I use #singleton object in my handler ?

PanelClickEventHandler won't be injected if you create it with new PanelClickEventHandler. It'll only be if GIN (or whatever you use for dependency injection) creates the instance, or if you explicitly inject its members afterwards.

Related

How do I use Mockito to mock a protected method?

I’m using Mockito 1.9.5. How do I mock what is coming back from a protected method? I have this protected method …
protected JSONObject myMethod(final String param1, final String param2)
{
…
}
However, when I attempt to do this in JUnit:
final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);
final String pararm1 = “param1”;
Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);
On the last line, I get a compilation error “The method ‘myMethod’ is not visible.” How do I use Mockito to mock protected methods? I’m open to upgrading my version if that’s the answer.
This is not an issue with Mockito, but with plain old java. From where you are calling the method, you don't have visibility. That is why it is a compile-time issue instead of a run-time issue.
A couple options:
declare your test in the same package as the mocked class
change the visibilty of the method if you can
create a local (inner) class that extends the mocked class, then mock this local class. Since the class would be local, you would have visibility to the method.
Responding to the request for a code sample of option 3 from John B's answer:
public class MyClass {
protected String protectedMethod() {
return "Can't touch this";
}
public String publicMethod() {
return protectedMethod();
}
}
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
class MyClassMock extends MyClass {
#Override
public String protectedMethod() {
return "You can see me now!";
}
}
#Mock
MyClassMock myClass = mock(MyClassMock.class);
#Test
public void myClassPublicMethodTest() {
when(myClass.publicMethod()).thenCallRealMethod();
when(myClass.protectedMethod()).thenReturn("jk!");
}
}
You can use Spring's ReflectionTestUtils to use your class as it is and without needing of change it just for tests or wrap it in another class.
public class MyService {
protected JSONObject myProtectedMethod(final String param1, final String param2) {
return new JSONObject();
}
public JSONObject myPublicMethod(final String param1) {
return new JSONObject();
}
}
And then in Test
#RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
#Mock
private MyService myService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(myService.myPublicMethod(anyString())).thenReturn(mock(JSONObject.class));
when(ReflectionTestUtils.invokeMethod(myService, "myProtectedMethod", anyString(), anyString())).thenReturn(mock(JSONObject.class));
}
}
Something like following worked for me, using doReturn() and Junit5's ReflectionSupport.
[Note: I tested on Mockito 3.12.4]
ReflectionSupport.invokeMethod(
mymock.getClass()
// .getSuperclass() // Uncomment this, if the protected method defined in the parent class.
.getDeclaredMethod("myMethod", String.class, String.class),
doReturn(myData).when(mymock),
param1,
param2);
John B is right, this is because the method you're trying to test is protected, it's not a problem with Mockito.
Another option on top of the ones he has listed would be to use reflection to gain access to the method. This will allow you to avoid changing the method you are testing, and avoid changing the pattern you use to write tests, and where you store these tests. I've had to do this myself for some tests where I was not allowed to change the existing code base which included a large number of private methods that needed to be unit tested.
These links explain Reflection and how to use it very well, so I will link to them rather than copy:
What is reflection and whit is it useful
How to test a class that has private methods, fields, or inner classes
WhiteBox.invokeMethod() can be handy.
public class Test extend TargetClass{
#Override
protected Object method(...) {
return [ValueYouWant];
}
}
In Spring, you can set it high high-priority like this:
#TestConfiguration
public class Config {
#Profile({"..."})
#Bean("...")
#Primary // <------ high-priority
public TargetClass TargetClass(){
return new TargetClass() {
#Override
protected WPayResponse validate(...) {
return null;
}
};
}
}
It is the same to override the origin bean.

jodd cannot manage to inject two beans

I have a DAO and a Service class each implements a interface:
public interface TemperatureDao extends GenericDAO<TemperatureLog> {
public abstract List<TemperatureLog> getLastHourTemperatures();
}
#PetiteBean(value="temperatureDao",wiring=WiringMode.AUTOWIRE)
public class TemperatureDaoImpl extends GenericAbstractDAO<TemperatureLog> implements TemperatureDao {
#Override
public List<TemperatureLog> getLastHourTemperatures(){
//do stuff here
return temps;
}
}
and
public interface TemperatureService {
public abstract boolean save(TemperatureLog t);
public abstract List<TemperatureLog> getLastHoutTemperatures();
}
#PetiteBean(value="temperatureService",wiring=WiringMode.AUTOWIRE)
public class TemperatureServiceImpl extends GenericService implements TemperatureService {
#PetiteInject
private TemperatureDao temperatureDao;
public TemperatureDao getTemperatureDao() {
return temperatureDao;
}
public void setTemperatureDao(TemperatureDao temperatureDao) {
this.temperatureDao = temperatureDao;
}
#Override
public boolean save(TemperatureLog t){
try {
temperatureDao.saveOrUpdate(t);
return true;
}catch(Exception e) {
return false;
}
}
#Override
#Transaction(propagation = JtxPropagationBehavior.PROPAGATION_REQUIRED, readOnly = true,isolation=JtxIsolationLevel.ISOLATION_READ_COMMITTED)
public List<TemperatureLog> getLastHoutTemperatures(){
return temperatureDao.getLastHourTemperatures();
}
}
and the problem is that temperatureDao is not injected as i get NullPointerException here:
return temperatureDao.getLastHourTemperatures();
The logs looks fine to me :
127 [DEBUG] j.p.PetiteBeans.registerPetiteBean:244 - Registering bean: temperatureDao of type: TemperatureDaoImpl in: SingletonScope using wiring mode: AUTOWIRE
128 [DEBUG] j.p.ProxettaBuilder.process:187 - processing: ro/videanuadrian/smartHome/dao/impl/TemperatureDaoImpl
128 [DEBUG] j.p.ProxettaBuilder.define:228 - proxy not applied ro.videanuadrian.smartHome.dao.impl.TemperatureDaoImpl
134 [DEBUG] j.p.PetiteBeans.registerPetiteBean:244 - Registering bean: temperatureService of type: TemperatureServiceImpl in: SingletonScope using wiring mode: AUTOWIRE
135 [DEBUG] j.p.ProxettaBuilder.process:187 - processing: ro/videanuadrian/smartHome/services/impl/TemperatureServiceImpl
139 [DEBUG] j.p.ProxettaBuilder.define:243 - proxy created ro.videanuadrian.smartHome.services.impl.TemperatureServiceImpl
So, any idea what I'm I missing here?
I am posting new answer to explain better what is going on.
What happens here is that you have proxy created on TemperatureServiceImpl and registered it as a PetiteBean, which is perfectly correct :) So, Petite container gets the proxified class, which is a subclass of your service implementation.
When Petite does the wiring, it is scanning the proxy class and, therefore, it can not see the annotated private field in the super class (which is the original TemperatureServiceImpl).
You can fix this in two ways:
either by removing private modifier (and use anything else) - than container will 'see' the field in the subclass, or
simply annotating the e.g. getTemperatureDao() method with #PetiteInject and leaving the field as it is.
Hope this explains what is going on. I will try to address this in upcoming 3.6 release.
Solved, the issue was that temperatureDao was declared as private. I have change it to default and now it works.

Windsor, inject container in class

Hi have the following component registered into Castle Windsor:
public class CommandDispatcher : IServiceCommandDispatcher
{
private readonly IWindsorContainer container;
public CommandDispatcher(IWindsorContainer container)
{
this.container = container;
}
#region IServiceCommandDispatcher Members
public void Dispatch<TCommand>(TCommand command) where TCommand : IServiceCommand
{
var handler = container.Resolve<IServiceCommandHandler<TCommand>>();
handler.Handle(command);
}
#endregion
}
And the dispatcher is registered in the following way:
Component
.For<IServiceCommandDispatcher>()
.ImplementedBy<CommandDispatcher>(),
But the field container is null when I resolve an instance of the dispatcher.
What should I do in order to pass the container to the resolved children items?
Windsor solves this problem for you with the Typed Factory Facility.
In the below example I want the implementation of ICommandHandlerFactory to resolve my command handler from my windsor container.
class CommandDispatcher : IServiceCommandDispatcher
{
private readonly ICommandHandlerFactory factory;
public CommandDispatcher(ICommandHandlerFactory factory)
{
this.factory = factory;
}
public void Dispatch<T>(T command) where T : IServiceCommand
{
var handler = this.factory.Create(command);
handler.Handle(command);
this.factory.Destroy(handler);
}
}
To achieve this I only need to create the ICommandHandlerFactory Interface.
public interface ICommandHandlerFactory
{
Handles<T> Create<T>(T command) where T : IServiceCommand;
void Destroy(object handler);
}
No implementation of ICommandHandlerFactory is required as Windsor will create the implementation. Windsor uses the convention that a method that returns an object is a resolve method and a method that returns void is a release method.
To register the factory you need to include using Castle.Facilities.TypedFactory and then register your factory as follows
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ICommandHandlerFactory>()
.AsFactory()
);
Just to reiterate you do not have to write any implementation code for your factory.
This works:
container.Register(Component.For<IWindsorContainer>().Instance(container));
It's not ideal, because you still have to call the Resolve method. There may be a better way to do this, using a factory. This looks similar to what you're trying to do:
http://kozmic.net/2010/03/11/advanced-castle-windsor-ndash-generic-typed-factories-auto-release-and-more/

JMockit mock protected method in superclass and still test method in real child class

I am still learning JMockit and need help understanding it.
I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session.
The method I want to bypass the struts session stuff inside the protected method.
public class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
public abstract class MySuperClass{
//I want to mock this method
protected Object myProtectedSuperClassMethod(){
// struts action context code that returns an object//}
}
Test code
#Test
public void testRunsAndDoesntPass() {
Mockit.setUpMock(MySuperClass.class, new MySuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}
});
// real class method invocation happens
assertEquals(expected, actual);
}
I keep getting NullPointers just like if I didn't have the mock
Not sure what to try next. All the docs and code samples I have read say to just declare the superclass method as public in the setUpMock and it should work.
I can't mock the entire class because that is the class I am testing.
I discovered that I needed to create the MockClass then reference it using setupmock correctly.
I am really falling in love with JMockit.
#MockClass(realClass = MyExtendingClass.class)
public static class MockSuperClass {
final Object object = new Object();
#Mock
public Object myProtectedSuperClassMethod() {
return object;
}}
#Test
public void testRunsAndNowWillPass() {
Mockit.setUpMock(MySuperClass.class, new MockSuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}});
// real class method invocation happens where i set expected and actual
assertEquals(expected, actual);
}
you mask the parent class implementation out totally #Mocked final MySuperClass base
abstract class MySuperClass{
protected Object myProtectedSuperClassMethod(){
}
class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
#Test
public void testRunsAndDoesntPass(#Mocked final MySuperClass base ) {
//you could mask out all the base class implementation like this
new Expectations(){{
invoke(base, "myProtectedSuperClassMethod");
}};
// real class method invocation happens
// ...
assertEquals(expected, actual);
}

Windsor: How can I make windsor dispose a transient component when not tracking component lifecycle?

We are using the NoTrackingReleasePolicy on the Windsor container due to the memory leaks that occur when we do not Release our components after usage. Now consider the following problem.
Some disposable component:
public class DisposableComponent : IDisposable
{
private bool _disposed;
public bool Disposed
{
get { return _disposed; }
}
public void Dispose()
{
_disposed = true;
GC.SuppressFinalize(this);
}
}
Some class using the disposable component:
public class ClassWithReferenceToDisposableService
{
private DisposableComponent _disposableComponent;
public ClassWithReferenceToDisposableService(DisposableComponent disposableComponent)
{
_disposableComponent = disposableComponent;
}
}
And finaly a test which configures these components as transient and resolve/release them:
[Test]
public void ReleaseComponent_ServiceWithReferenceToTransientDisposable_TransientComponentDisposed()
{
// arrange
var windsorContainer = new WindsorContainer();
windsorContainer.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
windsorContainer.Register(Component.For<ClassWithReferenceToDisposableService>().LifeStyle.Transient);
windsorContainer.Register(Component.For<DisposableComponent>().LifeStyle.Transient);
ClassWithReferenceToDisposableService service =
windsorContainer.Resolve<ClassWithReferenceToDisposableService>();
// act
windsorContainer.Release(service);
}
Now, if I remove the NoTrackingReleasePolicy, Windsor will dispose the transient service as expected, but I can not do this (period). Now, what I want to achieve is that Windsor disposes the transient components (anywhere in the resolve graph) when I invoke ReleaseCompnent. Is there any way to achieve this without changing the NoTrackingReleasePolicy?
No, you can't have your cake and eat it too.
You can implement your own custom policy that is kind of like NoTrackingReleasePolicy but will track some components...