alibaba / testable-mock

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

如果spring采用接口,impl实现类的方式,mock不生效 #282

Closed endsock closed 2 years ago

endsock commented 2 years ago

image spring目录是这样的,mock不生效

类文件

    @Override
    public String mockThis(String a){
        return a;
    }

    @Override
    @DataSource(SYSTEM_CENTER_SLAVE)
    public List<K8sDeployLogEntity> getDeployListByWfCode(OneParamForString oneParamForString) {
        System.out.println(mockThis("method:getDeployListByWfCode"));
        return k8sDeployLogDao.selectList(new LambdaQueryWrapper<K8sDeployLogEntity>().eq(K8sDeployLogEntity::getWfTaskCode,oneParamForString.getParam()));
    }

测试文件

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:conf/core/servlet.xml"})
public class K8sDeployLogServiceTest {
    @Autowired
    private K8sDeployLogService k8sDeployLogService;

    @MockDiagnose(LogLevel.VERBOSE)
    public static class Mock {
        @MockInvoke(targetClass = K8sDeployLogServiceImpl.class)
        public String mockThis(String a){
            return "haha";
        }
    }

//    @Before
//    public void init(){
//        MockitoAnnotations.initMocks(this);
//    }

    @Test
    public void getDeployListByWfCode() {
        //when(k8sDeployLogService.mockThis(anyString())).thenReturn("haha");
        OneParamForString oneParamForString = new OneParamForString();
        oneParamForString.setParam("gFgfmdpjo");
        K8sDeployLogEntity k8sDeployLogEntity = OmniConstructor.newInstance(K8sDeployLogEntity.class);
        System.out.println(RezenJsonUtil.toJSONString(k8sDeployLogEntity));
        String jsonStr = RezenJsonUtil.toJSONString(k8sDeployLogService.getDeployListByWfCode(oneParamForString));
        System.out.println(jsonStr);
        System.out.println(k8sDeployLogService.mockThis("ssss"));
    }

    @Test
    public void getDeployImgsInfo() {
    }
}

@MockInvoke(targetClass = K8sDeployLogService.class) 也试过了,mock都不生效

linfan commented 2 years ago

K8sDeployLogServiceTest类型中的Mock类在测试运行的时候默认只会关联到K8sDeployLogService接口类,因此其中的Mock方法不会对K8sDeployLogServiceImpl里的代码生效。

这种情况下如果要使用TestableMock,一种办法是测试类使用K8sDeployLogServiceImplTest,另一种办法是在测试目录下单独创建K8sDeployLogServiceImplMock类,然后为K8sDeployLogServiceTest类型加上@MockWIth(K8sDeployLogServiceImplMock.class)注解,具体参考:非标准位置的测试类