spring集成TestNg测试

1,在eclipse中安装TestNg插件,这里省略。。

2,编写测试spring Dao层的代码

package test.com.smart.dao;


import com.smart.dao.UserDao;
import com.smart.domain.User;
import com.smart.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

import java.util.Date;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

@ContextConfiguration(locations = {"classpath:resources/applicationContext.xml"})
public class UserDaoTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private UserDao userDao;

    @Test
    public void hasMatchUser() {
        int count  = userDao.getMatchCount("admin1", "123456");
        assertTrue(count>0);
    }

    @Test
    public void findUserByUserName() {
        User user = userDao.findUserByUserName("admin");
        assertNotNull(user);
        assertEquals(user.getUserName(), "admin");
    }

}

注意:@ContextConfiguration(locations = {"classpath:resources/applicationContext.xml"})这个注解是的localtion属性使用的是src类路径下面的

resources/applicationContext.xml spring配置文件

2,由于TestNg测试持久层和测试服务层十分类似,这里省略了,这里给出测试层的代码

a,项目编写封装了客户端请求的类

package com.smart.web;

public class LoginCommand {

    private String userName;

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}
b.下面编写控制类的代码

package com.smart.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.smart.domain.User;
import com.smart.service.UserService;

@Controller
@RequestMapping(value = "/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login.html")
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
        boolean isValidUser =
                userService.hasMatchUser(loginCommand.getUserName(),
                        loginCommand.getPassword());
        if (!isValidUser) {
            return new ModelAndView("login", "error", "用户名或密码错误。");
        } else {
            User user = userService.findUserByUserName(loginCommand
                    .getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());
            userService.loginSuccess(user);
            request.getSession().setAttribute("user", user);
            return new ModelAndView("main");
        }
    }
}
c,编写好控制类的代码,我们就可以测试这个控制类了,下面的代码是使用TestNg测试controller十分正确

package test.com.smart.web;

import com.smart.domain.User;
import com.smart.web.LoginController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

@ContextConfiguration(locations = {"classpath:applicationContext.xml","file:d:/actionSpring/chapter/chapter1/src/main/webapp/WEB-INF/viewspace-servlet.xml"})
public class LoginControllerTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private AnnotationMethodHandlerAdapter handlerAdapter;
    @Autowired
    private LoginController controller;
	//声明Request与Response模拟对象
	private MockHttpServletRequest request;
	private MockHttpServletResponse response;

	//执行测试前先初始模拟对象
	@BeforeMethod
	public void before() {
		request = new MockHttpServletRequest();
		request.setCharacterEncoding("UTF-8");
		response = new MockHttpServletResponse();
        request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true); //Spring3.1 存在的BUG

	}

	// 测试LoginController#loginCheck()方法
	@Test
	public void loginCheck() throws Exception {
        //测试登陆成功的情况
	    request.setRequestURI("/admin/loginCheck.html");
		request.addParameter("userName", "admin"); // 设置请求URL及参数
		request.addParameter("password", "123456");

		//向控制发起请求 ” /loginCheck.html”
		ModelAndView mav = handlerAdapter.handle(request, response, controller);
		User user = (User) request.getSession().getAttribute("user");
		assertNotNull(mav);
		assertEquals(mav.getViewName(), "main");
		assertNotNull(user);
        request.getSession().removeAttribute("user");

        //测试登陆失败的情况
        request.setRequestURI("/admin/loginCheck.html");
        request.addParameter("userName", "test");
        request.addParameter("password", "123456");

        mav = handlerAdapter.handle(request, response, controller);
        user = (User) request.getSession().getAttribute("user");
        assertNotNull(mav);
        assertEquals(mav.getViewName(), "login");
        assertNull(user);

	}
	


}
注意:
  1. @ContextConfiguration(locations = {"classpath:applicationContext.xml","file:d:/actionSpring/chapter/chapter1/src/main/webapp/WEB-INF/viewspace-servlet.xml"})  这个注解可以整合多个spring配置文件中"file:d:/actionSpring/chapter/chapter1/src/main/webapp/WEB-INF/viewspace-servlet.xml"表示的是文件系统的形式给出配置文件 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值