user972276
user972276

Reputation: 3053

mocking an autowired object in a test

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 
}

Upvotes: 0

Views: 524

Answers (2)

Tnadev
Tnadev

Reputation: 10112

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.

Upvotes: 1

Rogério
Rogério

Reputation: 16390

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.

Upvotes: 0

Related Questions