Search code examples
javajunitmockitojunit4

Mocked class method is not returning expected value with Mockito when then


Here is my controller class for which I am writing unit tests:

@RestController
@RequestMapping("document")
public class DocumentController {

    private final Logger logger = LoggerFactory.getLogger(DocumentController.class);
    
    private final PtfCommonService ptfCommonService;
    private final DocumentService documentService;
    
    @Autowired
    public DocumentController(PtfCommonService ptfCommonService, DocumentService documentService) {
        this.ptfCommonService = ptfCommonService;
        this.documentService = documentService;
    }
    
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = "application/json")
    public String create(@RequestBody String documentInfo) {
        System.out.println(this.documentService.getClass());
        return new Gson().toJson(this.documentService.createDocument(documentInfo));
    }
}

Here is my service class which is implementing the DocumentService interface:

@Lazy
@Service
public class DocumentServiceImpl implements DocumentService {
    
    @Override
    public JsonResponse createDocument(String documentInfo) {
        return saveDocument(documentInfo, false);
    }
}

Test class that contains the unit tests of DocumentController:

@RunWith(MockitoJUnitRunner.class)
//@ContextConfiguration(value = "classpath:applicationContext.xml")
public class DocumentControllerTest extends TestCase {
    
    @Mock
    DocumentService documentService;
    
    @InjectMocks
    DocumentController documentController;

    @Before
    @Override
    public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
    }
    
    /**
     * Test method to verify the functionality of createDocumnet controller method.
     */
    @Test
    public void createDocumentTest () {
        
        String documentInfo = "testInfo";
        JsonResponse jsonResp = new JsonResponse();
        jsonResp.setMessage("OK");
        jsonResp.setStatus("OK");
        jsonResp.setSuccess(true);
//      Mockito.when(documentService.createDocument(Mockito.anyString())).thenReturn(jsonResp);
        Mockito.when(documentService.createDocument(documentInfo)).thenReturn(jsonResp);
        String jsonResponse = documentController.create(documentInfo);
        System.out.println(jsonResponse);
        assertEquals(jsonResponse, jsonResponse);
    }
}

This is the exception I am getting when I run the test:

unnecessary Mockito stubbings(com.persivia.ptf.patientservice.controller.DocumentControllerTest)  Time elapsed: 0.511 sec  <<< ERROR!
org.mockito.exceptions.misusing.UnnecessaryStubbingException: 
Unnecessary stubbings detected in test class: DocumentControllerTest
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):

Pom.xml file that has required dependencies

<!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
        <!-- Mockito -->
        <dependency>
          <groupId>org.mockito</groupId>
              <artifactId>mockito-core</artifactId>
              <version>2.28.2</version>
              <scope>test</scope>
        </dependency>

Solution

  • If you duplicate Mockito setup by including both MockitoAnnotations.initMocks(this) and @RunWith(MockitoJUnitRunner.class) Mockito get's confused, and expects the mocked method to be called twice.