Java 求教,如果通过前端让 junit 方法以 junit 框架运行

自娱自乐 · 2021年12月06日 · 最后由 自娱自乐 回复于 2021年12月08日 · 1926 次阅读

代码如上,我想通过前端调用 openMianAccount()方法的时候,能把 @Before 的方法也执行了。
但是本人百度能力弱,没有找到~ 请教下
有没有懂得大佬
告诉我百度关键字也行

共收到 6 条回复 时间 点赞

@Before 的识别是 junit 执行器自己识别的。

要不你手动重新实现一个执行器,自动根据注解判定
要不你通过调用 junit 执行器提供的方法来执行指定用例,而非直接调用类里面的方法

对于第二种方法,百度关键字 函数调用 junit 也可以找到,参考结果:https://blog.csdn.net/haorenmin2008/article/details/44491331

应该不行

  1. 测试代码和业务代码分开,解耦。
  2. 你的需求会影响接口性能。
  3. 你的需求属于两个执行环境,一个在 spring 容器,一个是 junit 类加载器加载,不在一个容器。

如果要做一些拦截(你自己的验证逻辑)

spring 5.x 之后版本

  1. 实现 AsyncHandlerInterceptor,写自己的业务逻辑.
  2. 重写 preHandle/postHandle/afterCompletion 任意一个或某几个或全部方法。可以试试(我没试过)new JUnitCore().run(Request.method(ATest.class, "测试功能1"));
  3. 实现 WebMvConfigure。
  4. 重写 addInterceptors 并注册你写的拦截器。

spring 5.x 之前版本

  1. 继承 HandlerInterceptorAdaptor。
  2. 继承 WebMvcConfigureAdaptor。

spring 5.x 为例

@Component
public class CommonInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO 你的验证逻辑
        System.out.println(request.getRequestURI());
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        System.out.println(handlerMethod.getMethod().getName());
        return false;
    }
}
@Configuration
public class CommonWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(new CommonInterceptor());
    }
}
卡农Lucas 回复

你不是转开发了么。。。

恒温 回复

嗯。回答一下题主的问题。也舍不得 @ 恒温(张老板)。

陈恒捷 回复

感谢大佬,能达到预期效果。

只不过要想个办法解决前端传参问题~
控制器方法代码:

    @ResponseBody
    @RequestMapping("/demoJunit")
    public String demoJunit(){
        new DemoRun().demoruncase();
        return "执行成功";
    }

控制器方法调用的方法
```java
public class DemoRun {

    public void demoruncase(){
        new Thread(){
            public void run(){
                new JUnitCore().run(Request.method(demoCase.class,"openMianAccount"));
            }
        }.start();
    }

    public static void main(String[] args) {
        new DemoRun().demoruncase();
    }
}


实际执行代码
```java
public class demoCase {

    @Before
    public void login(){
        openUrl();
        LoginBusiness.login("HSG013","123456");

    }


    //定期
    @Test
    public void openMianAccount(){
        openPage("0125300");
        String s = new Business0125300().openMainAccount("851000000868");
        //案例执行完重置打开窗口数
        resetIframeNum();
    }

}
自娱自乐 关闭了讨论 12月08日 18:03
自娱自乐 重新开启了讨论 12月08日 18:03
卡农Lucas 回复

感谢大佬提供的多种思路,和回答的这么详细~
愿社区繁荣~

自娱自乐 关闭了讨论 12月08日 18:05
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册