Tonyukuk
Tonyukuk

Reputation: 6195

how to use @Autowired in the test methods

I am not able to use Spring's @Autowired annotations in the test methods.I am using JUnit for testing. @Autowiring works for normal classes in the beans but it does not work with the test methods. As I read in the forums, I have to implement spring-test in the pom.xml. I am still not able to auto wire and inject dependency of my service bean . Could you please help me to use dependency injection in the test class as I use dependency injection in my source classes.

Regards Alper

Upvotes: 1

Views: 11305

Answers (1)

bpedroso
bpedroso

Reputation: 4897

if you are writing unit tests a recommend you use @Mock and @InjectMocks.

You can annotate your test classes to run with MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class TestClass{
  @Mock
  private MockedClass;
  @InjectMocks
  private TestedClass;
}

But if you really want test all the flow and need to inject classes, you can @RunWith(SpringJUnit4ClassRunner.class) and @Autowired your classes.


Update:

Try adding this dependency on your spring boot application (don't need to add the version) to use SpringJUnit4ClassRunner:

groupId: org.springframework.boot 
artifactId: spring-boot-starter-test 
scope: test 
version: 1.4.4

Upvotes: 2

Related Questions