Junit模拟JNDI数据源

一、Junit4+spring-test测试web工程Controller层功能

1、新建测试基类,指定配置文件路径

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-*.xml" })
public class BaseTest {

}
2、新建controller测试类,继承测试基类

import static org.junit.Assert.*;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

import com.fit.BaseTest;

public class UserControllerTest extends BaseTest {

	@Autowired
	private UserController controller;

	@Test
	public void testLoginCheck() {
		//模拟HttpServletRequest、HttpServletResponse
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter("id", "18");
		request.addParameter("name", "jack");
		MockHttpServletResponse response = new MockHttpServletResponse();
		//
		ModelAndView mv = controller.loginCheck(request, response);
		assertEquals("main", mv.getViewName());
	}
}
3、Run As Junit Test

二、Junit4+spring-test模拟JNDI数据源

1、新建测试基类,指定配置文件,模拟jndi数据源

import javax.sql.DataSource;

import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-*.xml" })
public class BaseTest {

	@BeforeClass
	public void init() {
		DataSource ds = create a datasource;
		SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
		builder.bind("jndi-datasource-name", ds);
		builder.activate();
	}
}
2、新建web功能测试类

同上

3、Run As Junit Test


你可能感兴趣的:(Java)