alibaba / testable-mock

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

SSM框架下mock不生效 #276

Open hello-fk opened 2 years ago

hello-fk commented 2 years ago
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = XXX.class)
public class DemoTest {
    @Autowired
    ServiceA   serviceA;
    public static class Mock{
        @MockInvoke(targetClass = JsonUtil.class)
        private String toJson(AAo  aAo){
            return "123";
        }
        @MockInvoke(targetClass = ServiceB.class)
        private String methodB(AAo  aAo){
            return "123";
        }
    }

    @Test
    public void test(){
        AAo  aAo= new AAo();
        serviceA.methodA(aAo);
    }
}

@Controller
@RequestMapping("/")
public class ServiceA{
    @Autowired
    private ServiceB serviceB;

    @PostMapping("/")
    @Override
    public void methodA(AAo  aAo){
        logger.info(serviceB.methodB(aAo));
        logger.info( JsonUtil.toJson(aAo));
    }

}

tojson方法并没有被覆盖,serviceB的methodB方法也没有被覆盖

linfan commented 2 years ago

粗看起来应该是测试类没有按照 ”被测类+Test“ 约定命名导致Mock的关联没建立起来,可以把测试类的名字改为 ServiceATest,或者使用@MockWith注解来建立Mock关联

hello-fk commented 2 years ago

粗看起来应该是测试类没有按照 ”被测类+Test“ 约定命名导致Mock的关联没建立起来,可以把测试类的名字改为 ServiceATest,或者使用@MockWith注解来建立Mock关联

我刚才试了您说的两种方法,包括将测试类名称改为了ServiceATest,以及将Mock分离出去,并在测试类中用MockWith(Mock.class),但是都没有效果

hello-fk commented 2 years ago

粗看起来应该是测试类没有按照 ”被测类+Test“ 约定命名导致Mock的关联没建立起来,可以把测试类的名字改为 ServiceATest,或者使用@MockWith注解来建立Mock关联

不好意思,是因为公司框架的原因,需要在test文件夹下与被测试类的路径保持一致

riane2 commented 2 years ago

粗看起来应该是测试类没有按照 ”被测类+Test“ 约定命名导致Mock的关联没建立起来,可以把测试类的名字改为 ServiceATest,或者使用@MockWith注解来建立Mock关联

不好意思,是因为公司框架的原因,需要在test文件夹下与被测试类的路径保持一致

我试了一下,路径一直,好像还是不生效,能否在demo中提供springboot整合的demo,谢谢

riane2 commented 2 years ago

粗看起来应该是测试类没有按照 ”被测类+Test“ 约定命名导致Mock的关联没建立起来,可以把测试类的名字改为 ServiceATest,或者使用@MockWith注解来建立Mock关联

我刚才试了您说的两种方法,包括将测试类名称改为了ServiceATest,以及将Mock分离出去,并在测试类中用MockWith(Mock.class),但是都没有效果

不知道这个问题您解决了没,我也遇到了,如果有解决方案没可否共享一下,谢谢

linfan commented 2 years ago

@riane2 写了一个简单的参考示例 https://github.com/linfan/testable-spring-demo

Testable原理上是和运行框架无关的,不会受Spring、MyBatis或其他依赖影响。如果依然有问题,可以参考自助问题排查文档。