在测试类上添加@RunWith注解,指定使用SpringJunit的测试运行器,@ContextConfiguration注解指定测试使用的spring配置文件的位置,之后我们就可以注入我门需要测试的饿bean进行测试,(这里bean是dao),junit在运行测试之前会先解析spring配置文件,初始化spring配置中的bean。
<span style="font-family:Arial;"><span style="font-size:14px;">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context.xml"})
public class SpringJunitTest {
}</span></span><pre name="code" class="java"><span style="font-family:Arial;font-size:14px;">/**
* Junit单元测试
*/
public class TestTestTb extends SpringJunitTest {
@Autowired
private TestTbService dao;
@Test
public void testAdd() throws Exception {
TestTb testTb = new TestTb();
testTb.setName("测试数据");
testTb.setBirthday(new Date());
dao.addTestTb(testTb);
}
}</span>