0

I use Seam 2.2. I want to get a private field from a Seam component using Reflections. So I have:

    LocalizationEditActionRoot localizationEditActionRoot = (LocalizationEditActionRoot) Component
                        .getInstance(LocalizationEditActionRoot.class, true);
    Class currentClass = localizationEditActionRoot.getClass();
    WebDavMockClient mockClient = new WebDavMockClient();
    Field f = currentClass.getDeclaredField("davClient");
    f.setAccessible(true);
    f.set(localizationEditActionRoot, mockClient);

If I want to get a field called davClient(WebDavClient) I get a NoSuchFieldException. The field is of course injected. If i try something like this:

    Class currentClass = Class.forName("fr.isiom.bpms.admin.session.ext.action.root.LocalizationEditActionRoot");
    WebDavMockClient mockClient = new WebDavMockClient();
    Field f = currentClass.getDeclaredField("davClient");
    f.setAccessible(true);
    f.set(localizationEditActionRoot, mockClient);

I get the field davClient but the value isn't changed. He is still a instance of WebDavClient instead of WebDavMockClient. How can I change that field value?

spauny
  • 4,976
  • 9
  • 44
  • 61
  • What do you mean by "I get the field davClient but the value isn't changed"? Keep in mind that injection occurs around method invocation, so it might not fit well with reflection. – juanignaciosl Nov 10 '12 at 06:40
  • Are You using POJO's or EJB's? In the later be sure You're not working on a proxy or interface in stead of some implementation. – gadeynebram Nov 20 '12 at 18:57

1 Answers1

0

I haven't managed to do it with reflection. Instead I found a simpler idea/solution. In my test class, at Create/setUp method I get the sessionContext from Seam Context and change the webDavClient name to be bound with WebDavMockClient instead of WebDavClient. And this is how you solve this whole problem with a one-liner:

// Setting webDavClient to be injected by seam as WebDavMockClient to mock the actual delete
Contexts.getSessionContext().set("webDavClient", new WebDavMockClient());
spauny
  • 4,976
  • 9
  • 44
  • 61