本来以为在项目中集成进是比较容易的,真是不动手不知道,遇到的问题还是蛮多的,在尝试了junit和springmvc-test,最后成功集成进了testng,当然不断尝试的过程也是学习的过程,虽然不深入,也大体了解了他们的异同,好了上testng的步骤,内容还是基于前面四篇的工作。
一、引pom,注意:版本不同,jar包里面的类的使用稍有不同
<!-- test use only -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.4</version>
<scope>test</scope>
</dependency>
<!-- web项目的controller会用到 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- springmvc测试框架的一些配置注解 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<!-- json 字符串 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
二:添加使用的接口和类,自动生成见这里写链接内容
文件目录如图:
三.修改spring-mybatis.xml
注意:xml文件的名字、Dao类的名字、xml里面namespace的名字要保持一致,spring-mybatis.xml文件在被读取时就会处理你配置的所有mapper配置文件,因为我经常切换数据库,在mapper跟表数据不一致时会报错误Error parsing Mapper XML,所有我一般选择性的配置我需要的文件,看大家的实际场景和需求。
四:写测试类:
先看结果图:
AppBaseTest代码如下:
package com.template.baseTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
@ContextConfiguration(locations={
"classpath:spring-servlet.xml",
"classpath:spring.xml",
"classpath:spring-mybatis.xml"})
public abstract class AppBaseTest extends AbstractTestNGSpringContextTests {
//protected final Logger logger = LoggerFactory.getLogger(this.getClass());
}
BrandServiceImplTest的代码如下:
package com.template.ServiceImplTest;
import javax.annotation.Resource;
import org.testng.annotations.Test;
import com.google.gson.Gson;
import com.template.baseTest.AppBaseTest;
import com.template.entity.Brand;
import com.template.service.IBrandService;
public class BrandServiceImplTest extends AppBaseTest{
//private static Logger logger = Logger.getLogger(UserServiceImplTest.class);
private Gson gson = new Gson();
@Resource
private IBrandService brandService;
@Test
public void test2() {
Brand brand = brandService.getBranById(85);
System.out.println("*********************"+gson.toJson(brand));
}
}
五:在跑testng之前,
1.改下spring-servlert.xml,之前把数据库的配置文件以<context:property-placeholder location="classpath:jdbc.properties" />
的形式写入了spring.xml,结果在AppBaseTest里读不到,最后查阅资料换成了
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:freemarker.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
2.把log的输出级别该到了INFO,不然会有controller里的ftl找不到的异常出现,是debug级别的
六:右键测试类-run as testng