spring junit 测试

spring和junit测试

本指南将引导您完成创建Spring应用程序的过程,然后使用JUnit对其进行测试。

1.建立项目

 1)  通过idea建立spring的项目名称为testing-junit-web ,图1

图1 New Project

2)需要勾选spring web 图2

图2 需要勾选spring-web

3)目录结构 如图3 

自己建立了目录com.exapmple.demo的TestingJunitWebApplication.java,这个也是程序的入库

图3 目录结构

4)pom.xml的内容 如图4,自动把需要的junit 定义加上;

图4 pom.xml文件原内容

2.建立一个web服务 

2.1 编写代码HomeController.java 目的是获取user 信息

/**
 * Created by 风清扬 on 2020/1/12.
 */
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {

    @RequestMapping("/user")
    public @ResponseBody String getUser() {
        return "keny风清扬";
    }

}

2.2.运行,鼠标右键点击如图5

图5 运行Run TestingJunitWebAppliction

启动信息为:图6

图6 运行记录

可以看到,spring为2.2.2 版本,tomcat为9.0.29版本,端口为8080 默认端口,服务运行正常,用浏览器打开

http://localhost:8080/user 如图7 运行结果

图7 运行结果

3.测试用例

Spring解释@Autowired注释,在运行测试方法之前注入控制器。我们使用AssertJ(它提供asserttha()和其他方法)来表示测试断言。

3.1 新建一个冒烟测试SmokeTest.java

/**
 * Created by apple on 2020/1/12.
 */
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SmokeTest {

    //测试前注入
    @Autowired
    private HomeController controller;

    @Test
    public void contexLoads() throws Exception {
        assertThat(controller).isNotNull();
    }
}

运行方式用 ./mvnw test或者点击右键运行

3.2 建立一个HttpRequestTest.java

运行结果提示

Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
    at org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry.loadTestEngines(ServiceLoaderTestEngineRegistry.java:30)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.createListeners(JUnit5IdeaTestRunner.java:39)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

查看提示 2017.1.2 idea版本支持junit5的版本。需要升级idea或者是退回到junit4的版本。

解决方法:升级idea为2019.3的版本

图8 smoketest运行结果

mock的测试也通过 图

图9,mock测试结果

3.3 建立weblaytest

注意:代码中的用到的junt4的类,需要屏蔽一下

//Runwith是在junit4的方法
//@RunWith(SpringRunner.class)

运行结果如图10

图10 运行weblaytest的例子

3.4 新建一个service服务,

定义一个controller ,调用service的方法,返回 如图 11

图11 定义的webmocktest的返回结果

3.5 git 地址为:

https://github.com/mhxzkhl888888/spring-junit5-webdemo

 

发布了134 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/103945103