NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

Spring JUnit test autowired variable in tested class

I'd like to test a class which has a resource injected via @Autowired annotation.

class TestedClass{
  @Autowired
  private MyResource resource
  ...
}

How can I make this injection to work without modifying the tested class? The injection works fine in the test class, but not in the tested class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath*:/bean-definition.xml")
  public class TestedClassTest {
  TestedClass instance;

  //This works
  @Autowired
  private MyResource resource

  @Before
  public void setUp() throws Exception {
    instance = new TestedClass();
  }
...
}

So the problem is probably how to pass the context to the tested class?

Upvotes: 0

Views: 1276

Answers (1)

NimChimpsky
NimChimpsky

Reputation: 47300

inject TestedClass don't create with new(), I assume its a bean. Or inject myResource into testedClass using setter or constructor.

Upvotes: 1

Related Questions