Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@InjectMocks @Autowired together issue

could you help me please, some code:

@ContextConfiguration(locations = { "/applicationContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestUnit2 {

    @Mock
    private MongoOperations mongoTemplate;

    @InjectMocks
    @Autowired
    private WorkcircleRepositoryMongoImpl workCircleRepository;

    @Autowired
    private WorkcircleServiceImpl workCircleServiceImpl;

    @Before
    public void setUp() {

    ....
    when(mongoTemplate.findOne(new Query(), Person.class)).thenReturn(expectedPerson);
    MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {

    ... workCircleServiceImpl.find()...

    }

But test is failed:
NP in "... workCircleServiceImpl.find()..." line,

in separate way @InjectMocks & @Autowired work, but together are not worked.

like image 444
user3136131 Avatar asked Dec 14 '22 18:12

user3136131


1 Answers

Usually when you are unit testing, you shouldn't initialize Spring context. So remove Autowiring.

Usually when you do integration testing, you should use real dependencies. So remove mocking.

You are mixing integration and unit test here.

like image 87
luboskrnac Avatar answered Dec 22 '22 00:12

luboskrnac