0

I have a class defined in src/main/java:

Class A{
    @Autowired 
    B b; 
    public void method1() {}
} 

The corresponding test class is:

Class ATest {
    A a; 
    @Test
    public void method1Test() {}
}

B is null when ATest is unit tested. (run as junit test).

I only have spring-context library, and not spring boot application. Further, I have defined @ComponentScan(basePackage="com") and class A is inside of the same package.

Please let me know how to unit test in this scenario.

Guru
  • 2,739
  • 1
  • 25
  • 27

3 Answers3

1

For Spring dependencies I add to test class @Spy and @Autowired:

@Spy
@Autowired
private B b;

B will be available when testing A

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

Why do you define classes that are not unit tests in resource directory?

0

Mockito provides option to create spy on real objects. When spy is called, then actual method of real object is called.

@RunWith(MockitoJUnitRunner.class)
Class ATest {

    @Syp
    B b;

    @Test
    public void method1Test() {}
}
Kim
  • 4,080
  • 2
  • 30
  • 51