Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi I have a controller that I am trying to test, without mocking.

@Controller
public class MyController
{
    @Autowired
    private Type1 service1;

    @Autowired
    private Type2 service2;

    ....
} 

Test Class:

public class testController
{
    @Autowired
    private MyController controller;

    @Before
    public void setUp()
    {
        //setupStuff

    }

    @Test
    public void testControllerMethod()
    {
        //Test method
    }

}

When debugging through the test, I get the value for controller but the value for autowired service1 and 2 are null.

The xml file does have base packages for all the services and controller in <context: component-scan>

Which if removed gives me error creating bean. Even if i remove one of the service base packages.

Is there anything test specific I need to add to my configuration?

Type1:

public interface Type1
{
    String method1();
    String method2();
}

Type1 implementing class that is autowired is:

@Service
public class Type1Class implements Type1
{
    @Autowired
    private Type3 service3;

    //Methods implementatoin of Type1
}



Type2 is similar to this.
share|improve this question
Show us your config. For instances to be @Autowired, beans need to be declared or scanned for. – Sotirios Delimanolis 2 days ago
Show the source for Type1 and Type2. – GriffeyDog 2 days ago
I have the base package added to context:component-scanbase-package="package for controller, package for type1,.. etc". Do I need to add to this? – sorryconnect 2 days ago
I will add the mock of source as edit to the question. – sorryconnect 2 days ago
Have you annotated Type1 and Type2 with @Service? – GriffeyDog 2 days ago
show 1 more comment

1 Answer

Did you create setter method for @autowired variables?

share|improve this answer
No, but @Autowired work on private fields as well. Spring just goes and adds dependency injection in those fields. The only thing that it doesnt allow me to do is call that setter method. And as I dont have a usecase for it. – sorryconnect yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.