spring Junit+Web环境

Spring集成Junit

spring集成Junit的步骤:
1.导入spring集成Junit的坐标
2.使用@Runwith注解代替原来的运行期
3.使用@ContextConfiguration制定配置文件或配置类
4.使用@Autowired注入需要测试的对象
5.创建测试方法进行测试

<!--spring集成Junit需要导入的坐标-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.2.22.RELEASE</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

测试 创建测试类SpringJunitTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {

    @Autowired
    private UserService userService;

    @Test
    public void test1(){
        userService.save();
    }
}

spring集成web环境,配置Tomcat

UserDao,UserDaoImpl,UserService,UserServiceImp的类里面就是一个save()方法,applicationContext.xml配置文件配了useDao,userService的bean标签

web.xml配置servlet

<servlet>
  <servlet-name>UserServlet</servlet-name>
  <servlet-class>com.itheima.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>UserServlet</servlet-name>
  <url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</listener>

Spring提供获取应用上下文的工具

Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring的配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端供WebApplicationContextUtils供使用者获得应用上下文对象。
我们只需要做两件事:
1.在web.xml文件中配置ContextLoaderListener监听器(pom.xml导入spring-web坐标)
2.使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

pom.xml导入spring-web坐标:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

web.xml配置监听器:

<!--  监听器-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

UserServlet.java

public class UserServlet extends HttpServlet {
    @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       ServletContext servletContext = req.getServletContext();

        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);

        userService.save();
    }
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值