-2

With Junit 4 Autowired functionality was working fine. But once I migrated to Junit 5, I am not able to make Autowired work and there are lot of dependencies to make everything cover by mocking each object. Went through lot of websites and tried various annotations and dependencies, but still not able to make it work. Below is my Service implementation class.

@Service
public class DetailsServiceImpl implements IDetailsService {
    @Autowired
    FormatBO formatBO;
    
    public List<TestBean> fetchChargeDetails(TestBean bean){
        response = //api call
        
        List<TestBean> details = formatBO.fetchMoreDetails(response);
        return details;
    }
}

Below is my test class

@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
@RunWith(JUnitPlatform.class)
@ContextConfiguration(classes = {FormatBO.class,Mapper.class})
public class SimpleImplTest {
    
    @MockBean
    Mapper mapper;

    @Autowired
    FormatBO formatBO;
    
    @InjectMocks
    private DetailsServiceImpl service = new DetailsServiceImpl();
    
    static TestBean bean;
    
    @BeforeEach
    public void initData() {
        bean = new TestBean();
        bean.setCategoryId("1");
    }

    
    @Test
    public void getBasicDetailsTest(){
        service.fetchBasicDetails(bean);
    }
}

FormatBO.class is another class where other functionalities are there which I am trying to autowire, which is not happening. Instead getting null pointer when invoking fetchMoreDetails method since formatBO is null. Please help to fix this issue

Chethan
  • 73
  • 8

1 Answers1

-1

Try this:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {FormatBO.class,Mapper.class, DetailsServiceImpl.class})
public class SimpleImplTest {

    @MockBean
    Mapper mapper;

    @Autowired
    FormatBO formatBO;

    @Autowired
    private DetailsServiceImpl service;

    static TestBean bean;

    @BeforeEach
    public void initData() {
        bean = new TestBean();
        bean.setCategoryId("1");
    }


    @Test
    public void getBasicDetailsTest(){
        service.fetchBasicDetails(bean);
    }
}
bausov
  • 387
  • 3
  • 12