0

I have a Class that has a field that gets set through a spring bean and is annotated with @Autowired like so:

public class Foo {
    ....
    @Autowired
    private Bar bar;
    .... 
}

I now want to setup a JUnit test that tests some functionality that at some point will create a Foo object. I am not in control of when this Foo object is generated. What is the easiest way to mock this object so that anytime Foo gets instantiated, this object get populated with the mocked item? I am using a 3rd party library to mock the Bar object nicely, so I would prefer to do all of this in the Java test class without using xml files.

Everything I have found online seems to either involve creating an xml file or mocking a specific instance of the Class. Thank you all for your help!

I would like something like the following:

public class Test {
    private Bar mockedBar = createBar();
    // somehow set 'mockedBar' so that any Foo object
    // created always contains mockedBar 
}
user972276
  • 2,973
  • 9
  • 33
  • 46
  • Possible duplicate of [Make a class to be a Mockito mock without calling mock](http://stackoverflow.com/questions/32313362/make-a-class-to-be-a-mockito-mock-without-calling-mock) – JEY Oct 22 '15 at 13:11
  • The answer provided in that question would require me to create a Foo object in order to use the spy annotation. Unless, by creating the Foo object and using spy allows for any instantiation of Foo will set Bar to 'mockedBar' – user972276 Oct 22 '15 at 13:51
  • If there is some functionality, that creates Foo object, then Foo object is not a Spring managed bean. How are you setting bar in the real application? – jny Oct 22 '15 at 14:02
  • through applicationContext.xml. I could create a test-specific applicationContext file that contains the info, but the object I want to mock can easily be created through a 3rd party java call, createBar(). So, I would rather use that if possible. – user972276 Oct 22 '15 at 16:59

2 Answers2

1

I have written uch test with help of JMOCKIT,

Please read it might help you.

You just need to create object with overriding required methods.

Then use

  Deencapsulation.setfield(FIXTURE,new Bar(){

    //@Override you methods

});

FIXTURE is Object in which you want Bar instance available with mocked methods.

VedantK
  • 9,728
  • 7
  • 66
  • 71
0

With the JMockit mocking library, you could simply declare a mock field as @Capturing Bar anyBar in your test class. This should cause any current or future Bar instances to be mocked, even if they belong to some subclass of Bar.

Rogério
  • 16,171
  • 2
  • 50
  • 63