Home > Back-end >  Java mockito test method with void statements
Java mockito test method with void statements

Time:03-11

Below is my AppleServiceImpl class and a test class AppleServiceImpl which I created. During my testing,

  1. method creditCheck gets called
  2. we call the class and method appleService.creditCheck(request, response); to test.
  3. when credit check is called,the appleHelper object is null.doesnt get initalised.
  4. How do I mock it or work around it to get testing done?
public class AppleServiceImpl extends GenericService implements ApplicationService {

    @Autowired
    AppleHelper appleHelper;

    public void creditCheck(ApplicationRequest request, ResponseMessage<ApplicationResponse> response) {
        appleHelper.test123(request, response);
    }
}

public class AppleServiceImplTest {
    @Spy
    AppleServiceImpl appleService= new AppleServiceImpl ();
    @Test
    public void creditCheck() {
        appleService.creditCheck(request, response);
    }
}

CodePudding user response:

You probably want to add a constructor to AppleServiceImpl that takes AppleHelper as a parameter and autowire on the constructor. Next in your test you want to create an @Mock AppleHelper appleHelper field that you inject using @InjectMocks

  • Related