Warm tip: This article is reproduced from stackoverflow.com, please click
java junit mockito testing unit-testing

Unit test method does not use the mocked object when running the test. Instead calls the actual clas

发布于 2020-04-08 09:22:52

I have a class to test named ClassToTest. It calls a CloudService to upload file.

public class ClassToTest {
    public String moveFilesToCloud(String path, String documentclass, String objStore) {
        log.info("Moving files to cloud.");
        String docId = StringUtils.EMPTY;
        CloudService service = new CloudService();
        try {
            docId = service.uploadDocument(path,documentclass,objStore,"");
        } catch (CloudException e) {
            log.info("* Error uploading reports to cloud *" + e.getMessage());
        }
        return docId;
    }
}

Below is the test class. The test class has a mocked object for CloudService. When I run the test instead of getting the mocked object, the actual CloudService is executed and fails.

@Mock
CloudService cloudService;

@InjectMocks
ClassToTest classToTest;

@Test
public void testMoveFilesToCloud() throws Exception {
    String pass = "pass";
    when(cloudService.uploadDocument("abc","def","ghi","")).thenReturn(pass);

    String result = classToTest.moveFilesToCloud("abc","def","ghi");

    assertEquals(result,pass);
}

I am expecting the mocked object for CloudService to be used when executing this line -

CloudService service = new CloudService();

Instead, it is actually trying to create a new instance of CloudService.

Where am I going wrong here?

Questioner
Keerthi
Viewed
71
Willem 2020-02-01 06:07

Try to use dependency injection. Make CloudService a field of ClassToTest. Change the constructor of ClassToTest to accept a CloudService. Then Mockito is able to inject the mock into ClassToTest in your unit test.

public class ClassToTest {

    private CloudService service;

    public ClassToTest(CloudService service) {
        this.service = service;
    }

    public String moveFilesToCloud(String path, String documentclass, String objStore) {
        log.info("Moving files to cloud.");
        String docId = StringUtils.EMPTY;
        try {
            docId = service.uploadDocument(path,documentclass,objStore,"");
        } catch (CloudException e) {
            log.info("* Error uploading reports to cloud *" + e.getMessage());
        }
        return docId;
    }
}