Spring整合JUnit和Servlet

这篇具有很好参考价值的文章主要介绍了Spring整合JUnit和Servlet。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、Spring注解配置

@Component 组件

@Repository @Service @Controller

@Value @Autowired @Qualifier ~=== @Resource

@Bean

@ComponentScan @PropertySource @Configuration

@Import

@EnableTransactionManagement

AnnotationConfigApplicationContext

2、Spring整合Junit单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = 自己的主配置类.class)

一、Spring整合JUnit

1、Junit 简介

Junit 是 Java 编程语言的单元测试框架,用于编写和运行可重复的自动化测试。

单元测试(Unit Testing),是指对软件中的最小可测试单元进行检查和验证。对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如 C 语言中单元指一个函数,Java 里单元指一个类,图形化的软件中可以指一个窗口或一个菜单等。总的来说,单元就是人为规定的最小的被测功能模块。单元测试是在软件开发过程中要进行的最低级别的测试活动,软件的独立单元将在与程序的其他部分相隔离的情况下进行测试。

Junit 特点

Junit 是一个开放的资源框架,用于编写和运行测试。

提供注解来识别测试方法。

提供断言来测试预期结果。

Junit 测试允许你编写代码更快,并能提高质量。

Junit 优雅简洁。没那么复杂,花费时间较少。

Junit 测试可以被组织为测试套件,包含测试用例,甚至其他的测试套件。

Junit 在一个条中显示进度。如果运行良好则是绿色;如果运行失败,则变成红色。

2 、Junit 注解

spring集成servlet,spring,servlet,junit

 

3 、Junit 断言

JUnit4.4 引入了 Hamcrest 框架,它们用来帮助我们确定被测试的方法是否按照预期的效果正常工作,通常把这些辅助方法称为断言。Assert.

spring集成servlet,spring,servlet,junit

4、Junit 的使用

4.1 创建项目引入Jar 包依赖

junit-4.13.jar

hamcrest-core-1.3.jar

4.2 Junit 注解的使用

 

package com.dyh.test;

import org.junit.*;

public class TestJunit {
    @BeforeClass
    public static void init(){
        System.out.println("beforeClass");
    }

    @Before
    public void setUp(){
        System.out.println("before");
    }

    @Test
    public void test1(){
        System.out.println("test1");
    }
    @Test
    public void test2(){
        System.out.println("test2");
    }

    @After
    public void setDown(){
        System.out.println("after");
    }

    @AfterClass
    public static void destroy(){
        System.out.println("afterclass");
    }
}

spring集成servlet,spring,servlet,junit

4.3 Junit 断言的使用

 

 @Test
    public void test1(){
        System.out.println("test1");
        Assert.assertTrue(1==1);
    }
    @Test
    public void test2(){
        System.out.println("test2");
        Integer a = Integer.valueOf(127);
        Integer b = Integer.valueOf(127);
        System.out.println("eqauls:" + a.equals(b));
        System.out.println("a==b ?  " + (a == b));
        Assert.assertEquals(a, b);
        Assert.assertSame(a, b);
    }

    @Test
    public void test3(){
        System.out.println("test3");
        Integer a = Integer.valueOf(128);
        Integer b = Integer.valueOf(128);
        System.out.println("eqauls:" + a.equals(b));
        Assert.assertEquals(a, b);
        System.out.println("a==b ?  " + (a == b));
        Assert.assertNotSame(a, b);
    }

5、Spring 整合 Junit

// 更换测试引擎
@RunWith(SpringJUnit4ClassRunner.class)
// //指定 Spring  配置文件
@ContextConfiguration(classes = SpringConfiguration.class)
public class SpringJUnitTestAnTx {
    @Autowired
    private UsersService usersService;
    @Resource(name="users")
    private Users user;
    @Resource(name="orders")
    private Orders order;

    @Test
    public void testAddUsersAndOrders(){
        this.usersService.addUsersAndOrders(user, order);
    }

}

二、Spring整合Servlet

1、Jar 包依赖

Spring 核心容器模块

spring-beans-5.2.7.RELEASE.jar

spring-context-5.2.7.RELEASE.jar

spring-core-5.2.7.RELEASE.jar

spring-expression-5.2.7.RELEASE.jar

Commons-Loggin 日志

commons-logging-1.2.jar

Spring AOP 模块

spring-aop-5.2.7.RELEASE.jar

SpringWeb 模块

spring-web-5.2.7.RELEASE.jar

Servlet

servlet-api.jar

2、搭建环境

2.1 创建 Web 项目

spring集成servlet,spring,servlet,junit

在WEB-INF文件夹内新建lib文件夹,将jar粘贴进来,并且添加到项目中,如下操作

spring集成servlet,spring,servlet,junit 

spring集成servlet,spring,servlet,junit 

2.2 添加 Spring 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

 

3、在Web项目中启动Spring框架

在 Web 项目中需要在 web.xml 文件中配置启动 Spring 框架的监听器。用于启动 Spring框架。

修改 web.xml 文件

context-param : 指定配置文件的位置

listener:配置启动 Spring 框架的监听器 ContextLoaderListener

<?xml  version="1.0"  encoding="UTF-8"?>
<web-app  xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
          version="4.0">
    <!--指定配置文件的位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--配置启动 Spring 框架的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

 

4、在 Servlet 中获取 Bean 对象

4.1 创建持久层

public interface UsersDao {
    void insertUsers();
}

UsersDaoImpl.java:

@Repository
public class UsersDaoImpl implements UsersDao {
    @Override
    public void insertUsers() {
        System.out.println("insert  into  users....");
    }
}

4.2 创建业务层

UsersService.java:

public interface UsersService {
    void addUsers();
}

UsersServiceImpl.java:

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;
    public void setUsersDao(UsersDao usersDao) {
        this.usersDao = usersDao;
    }

    @Override
    public  void  addUsers()  {
        this.usersDao.insertUsers();
    }
}

4.3 创建 Servlet

package com.dyh.controller;

import com.dyh.service.UsersService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns  =  "/addUsers.do")
public  class  UsersServlet  extends  HttpServlet  {
    @Override
    protected void  doGet(HttpServletRequest req, HttpServletResponse
            resp)  throws  ServletException,  IOException  {
        this.doPost(req,  resp);
    }
    @Override
    protected  void  doPost(HttpServletRequest  req,
                            HttpServletResponse  resp)  throws  ServletException,  IOException  {
//方式一
/*  WebApplicationContext  webApplicationContext  =
(WebApplicationContext)
this.getServletContext().getAttribute(WebApplicationContext.ROOT_
WEB_APPLICATION_CONTEXT_ATTRIBUTE);
UsersService  usersService  =  (UsersService)
webApplicationContext.getBean("usersServiceImpl");
usersService.addUsers();*/
//方式二
        WebApplicationContext webApplicationContext  =
                WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        UsersService usersService  =  (UsersService)
                webApplicationContext.getBean("usersServiceImpl");
        usersService.addUsers();
        resp.getWriter().print("Hello  Servlet");
    }
}

4.4 修改Spring配置文件

<?xml  version="1.0"  encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
    <context:component-scan base-package="com.dyh.service.impl,com.dyh.dao.impl"/>
</beans>

1、Spring整合Junit单元测试

//更换测试引擎
@RunWith(SpringJUnit4ClassRunner.class)
//指定 Spring  配置文件
@ContextConfiguration(locations  =
{"classpath:applicationContext.xml"})

2、Spring整合Servlet

2.1 web.xml:

 <!--指定配置文件的位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--配置启动 Spring 框架的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

2.2 Servlet中获取webApplicationContext

WebApplicationContext  webApplicationContext  =WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

2.3 Spring 主配置文件文章来源地址https://www.toymoban.com/news/detail-765046.html

<context:component-scan
    base-package="com.dyh.service.impl,com.dyh.dao.impl"/>

到了这里,关于Spring整合JUnit和Servlet的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • spring-spring整合Junit

    1.导包 artifactIdspring-test/artifactId artifactIdjunit/artifactId 2.创建测试类

    2024年02月12日
    浏览(30)
  • 【四:Spring整合Junit】

    相同点 前面都一样和Spring整合mybatis(基于注解形式)一样 Spring整合Mybatis 不同点 1、导入依赖增加 2、编写的位置不同。。路径一定要与实现类一致

    2024年02月07日
    浏览(32)
  • Spring整合junit

    @RunWith   指定测试用例类型 @ContextConfiguration 指定测试SpringConfig配置类  @Autowired  自动装配 @Test  表明这个是测试用例

    2024年02月15日
    浏览(41)
  • Spring整合Junit框架

    在前面的文章中给大家介绍了 以注解和XML的方式分别实现IOC和依赖注入。并且我们定义了一个测试类,通过测试类来获取到了容器中的Bean,具体的测试类定义如下: 大家思考一下,定义这种测试代码有没有什么问题? 其实问题很明显,就是我们每次定义测试类,都需要去写

    2024年01月15日
    浏览(31)
  • Spring整合Junit单元测试

    在测试类中,每个测试方法都有以下两行代码: 这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它 将需要进行测试Bean直接在测试类中进行注入 ①导入spring集成Ju

    2024年02月12日
    浏览(33)
  • Spring整合Junit4

    好处1:不需要自己创建IOC容器对象了 好处2:任何需要的bean都可以在测试类中直接享受自动装配 ①加入依赖 ②创建测试类

    2024年02月20日
    浏览(38)
  • Spring Boot整合Junit

    2024年01月17日
    浏览(24)
  • Spring整合JUnit实现单元测试

    在软件开发过程中,单元测试是保证代码质量和稳定性的重要手段。JUnit是一个流行的Java单元测试框架,而Spring是一个广泛应用于Java企业级开发的框架。本文将介绍如何使用Spring整合JUnit实现单元测试,以及如何使用Mockito模拟依赖对象和使用Spring TestContext框架进行集成测试。

    2024年02月14日
    浏览(46)
  • Spring-集成Junit

    一、引子 我们在Spring概念中提到:Spring的一大优势在于可以集成众多优秀的框架。毫无疑问,我首先向读者推荐的就是Junti框架。因为我们在前期的学习中,写一些小的demo,用Junit来进行小测试是非常合适的。下面让我们来具体看看如何集成Junit。 二、Spring集成之前 我们首先

    2024年01月25日
    浏览(19)
  • Spring集成Junit

    目录 1、简介 2、Junit存在的问题 3、回顾Junit注解 4、集成步骤 4.1、导入坐标 4.2、@Runwith 4.3、@ContextConfiguration 4.4、@Autowired 4.5、@Test 4.6、代码 5、补充说明 5.1、@Runwith 5.2、BlockJUnit4ClassRunner 5.3、没有配置@Runwith  ⭐作者介绍:大二本科网络工程专业在读,持续学习Java,努力输出

    2024年02月14日
    浏览(16)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包