单元测试方法在运行测试时不使用模拟对象。而是调用实际的类和方法

时间:2020-01-31 21:56:08

标签: java unit-testing testing junit mockito

我有一个要测试的类,名为ClassToTest。它调用CloudService来上传文件。

try:
    raise CustomException(foo)
except CutomException as e:
    print(e.args)
    handle_exception()

class CustomException(Exception):
    def __init__(self, foo):
        super().__init__(foo, bar)

下面是测试课程。测试类具有CloudService的模拟对象。当我运行测试而不是获取模拟对象时,实际的CloudService被执行并且失败。

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;
    }
}

我希望执行此行时使用CloudService的模拟对象-

CloudService服务=新的CloudService();

实际上,它实际上是在尝试创建CloudService的新实例。

我在哪里错了?

2 个答案:

答案 0 :(得分:2)

尝试使用依赖注入。使CloudService成为ClassToTest的字段。更改ClassToTest的构造函数以接受CloudService。然后Mockito可以在单元测试中将模拟注入到ClassToTest中。

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;
    }
}

答案 1 :(得分:1)

这将不起作用。

如果您曾经使用过注射,那么添加@RunWith(MockitoJUnitRunner.class)会很有用,但没有用。

如果可以使用注入,则可以这样做,否则必须使用PowerMockito才能修改字节码并在调用构造函数时产生模拟。 This can help you

相关问题