alibaba / testable-mock

换种思路写Mock,让单元测试更简单
https://alibaba.github.io/testable-mock/
MIT License
1.83k stars 310 forks source link

MOCK类无法自动注入 #253

Closed wmx3ng closed 2 years ago

wmx3ng commented 2 years ago

问题描述

仅有依赖接口类(无实现,ICheckService) , mock后, 在实际业务类中, 没有自动注入.

场景描述

业务类 LogCheck:

public class LogCheck {
    private ICheckService checkService;

    public void setCheckService(ICheckService checkService) {
        this.checkService = checkService;
    }

    public String getCheckValue() {
        //TODO do something.
        return checkService.check1();
    }
}

依赖类ICheckService, 仅有接口

public interface ICheckService {
    String check1();
}

依赖类ICheckService的Mock类-ICheckServiceMock

public class ICheckServiceMock {
    @MockMethod(targetClass = ICheckService.class)
    public String check1() {
        return "mock#check1";
    }
}

测试类LogCheckTest:

@MockWith(ICheckServiceMock.class)
public class LogCheckTest {
    private LogCheck logCheck = new LogCheck();

    @Test
    public void check1() {
        String value = logCheck.getCheckValue();
        System.out.println("value = " + value);
    }
}

在测试执行中, 调到业务类: return checkService.check1(); 报了空指针异常, 请教下, 如何将mock类自动注入进来

LuuucasChen commented 5 months ago

请问是如何解决的