Spring3 + Mybatis3 + JUnit4 手动 getBean

上一篇 JUnit 测试类中 @Test 注解无效 import org.junit.Test 失败 中,虽然屁颠屁颠用 JUnit3.8.1 跑起来了,也算解决了项目实际需求。
但人总是不能安于现状嘛,JUnit3 毕竟太老了,JUnit5 暂时还玩不上,JUnit4还是应该跑一跑的。
于是继续:(注解还玩不转,先手动 getBean 跑起来再说 )

pom.xml 中先加依赖

hamcrest-core 在 junit 的依赖中有了。所以可以省了

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
	</dependency>
	<dependency>
		<groupId>org.hamcrest</groupId>
		<artifactId>hamcrest-library</artifactId>
		<version>1.3</version>
	</dependency>

在要测试的类上右键 》New 》Other

(当然如果你的右键菜单中有 【JUnit Test Case】 选项,就不用像我这样再打开 Other窗口了)
Spring3 + Mybatis3 + JUnit4 手动 getBean

  1. 选择 JUnit4
  2. 记得把文件存到 test 下面
    Spring3 + Mybatis3 + JUnit4 手动 getBean

直接上 Test Case 代码

package com.jerry.mapper;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*; // 这里直接静态引入,就可以不写类名,直接写方法了

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jerry.entity.Blog;

public class BlogMapperTest {
	//初始化上下文;//这里注意写你自己的文件所在。我的路径是 /jerry-JUnit/src/main/resources/applicationContext.xml
	static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
	private BlogMapper blogMapper;
    
	@Before
	public void setUp() throws Exception {
		// 测前准备
		blogMapper = (BlogMapper)context.getBean("blogMapper");
	}

	@After
	public void tearDown() throws Exception {
		// 测后扫尾
	}

	@Test
	public void testSelectList() {
		List<Blog> list = blogMapper.selectList();
		for (Blog blog : list) {
			assertThat("博文标题不得少于 6 个字" , blog.getBlogTitle().length(), greaterThan(6));
		}
	}

}

执行测试

左侧目录中找这个测试类。

  1. 在类上:右键》 Run As ,执行类中所有测试。
  2. 展开类,在测试方法上:右键》 Run As ,执行当前方法。
  3. 当然有 Run As 就有对应的 Debug As 这些就自己摸吧。

最后提醒(看结果的地方)

看测试结果在 JUnit 里,但是如果有日志输出,Console 就会自动跳出来 ,一开始我找JUnit的进度条,还以又出问题了。懵了一小会,哈哈哈哈
Spring3 + Mybatis3 + JUnit4 手动 getBeanSpring3 + Mybatis3 + JUnit4 手动 getBean