vendredi 31 janvier 2020

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

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?

Aucun commentaire:

Enregistrer un commentaire