Announcement Announcement Module
Collapse
No announcement yet.
Overwriting a single bean for test? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • BrandonY
    started a topic Overwriting a single bean for test?

    Overwriting a single bean for test?

    I have a very large application with a very large application-context.xml file. I have many unit tests, and occasionally I want to write a quick unit test that replaces any particular bean with a mocked out replacement. I see that it's quite possible to create separate application-contexts for testing that can override small pieces of application-context, but is there a way to do this inline from a unit test class file?

    In other words, if I have bean Foo, which has bean Baz as a property, which in turn has bean Bar as a property, and I want to replace Bar with mockBar for a single test, how could I do that?

    I'd like it to look something like this:

    Code:
    public void testSomething() {
      Bar mockBar = new Mock(Bar.class);
      
      context =
       createNewApplicationContextJustLikeOldOneExceptBarIs(mockBar);
    
      Foo foo = context.getBean("foo");
    }
    Can this be done cleanly? How is something like this normally handled?

  • nstoddar
    replied
    Normally, I'd say that you wouldn't use a mock unless you were doing a simple unit test (aka no Spring application context). If you absolutely had to, I'd guess that your beans just weren't developed very thoughtfully -- use a service locator so your class is more testable.

    That being said, I suppose you could write your own FactoryBean that creates a mock for a class, and include a definition in your spring config files so it overrides the original definition.

    Leave a comment:

Working...
X