1

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

Tonyukuk
  • 5,745
  • 7
  • 35
  • 63
  • 3
    You need to setup the context for tests in a similar way you do when running the app. There's a lot of info on http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html but in short, you should use @ContextConfiguration and @RunWith(SpringJUnit4ClassRunner.class). Also see http://stackoverflow.com/questions/2862888/how-to-create-testcontext-for-spring-test Sorry I don't have time for a full answer. Btw, I didn't downvote you. – kaqqao Mar 05 '17 at 12:34

1 Answers1

2

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
Brad Turek
  • 2,472
  • 3
  • 30
  • 56
bpedroso
  • 4,617
  • 3
  • 29
  • 34
  • Hello pedroso. I come across with java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionDefinition when I added @RunWith(SpringJUnit4ClassRunner.class). – Tonyukuk Mar 05 '17 at 16:47
  • Try add this dependency on your spring boot application (dont need to add the version): groupId: org.springframework.boot artifactId: spring-boot-starter-test scope: test version: 1.4.4 – bpedroso Mar 05 '17 at 19:15