您的位置:首页 > 编程语言 > Java开发

spring整合testng和junit

2013-11-28 17:02 330 查看
整合junit进行测试:

JUnit对Spring有天然的支持,只需添加两条Annotation就可以启动Spring Context了,示例代码如下:

@ContextConfiguration("/META-INF/spring/integration/inbound-gateway-config.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class InboundGatewayTests {

@Autowired
private SimpleWebServiceInboundGateway gateway;
}


整合testng进行测试:

与JUnit不同,TestNG没有提供@RunWith注解。TestNG的测试用例需要继承 org.springframework.test.context.testng.AbstractTestNGSpringContextTests或 org.springframework.test.context.testng.AbstractTestNGSpringContextTests来启动SpringContext,示例代码如下:

@ContextConfiguration(locations={"/WEB-INF/accountContext.xml"})
public class TestDao extends AbstractTestNGSpringContextTests {
@Autowired
JdbcTemplate jdbcTemplate;

@Test
public void init() throws ServletException {
try {
jdbcTemplate.execute("create table contacts (name varchar(45),email varchar(45),phone varchar(45))");
List list = jdbcTemplate.queryForList("select * from contacts");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}


以下讲解有关@ContextConfiguration参数的设置:

1. 不指定Context文件,@ContextConfiguration

Spring的 ContextLoader 会判断是否需要加载context,如果需要,默认加载器( GenericXmlContextLoader )会根据用例类名生成一个Spring Context配置文件的名字,例如,如果测试用例为 com.example.MyTest ,则 GenericXmlContextLoader会从“ classpath:/com/example/MyTest-context.xml”中加载Context。

2.指定多个Context文件 ,比如@ContextConfiguration("/META-INF/spring/integration/inbound-gateway-config.xml")

3.指定多个Context文件 ,比如@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})

ContextLoader会从classpath的根目录加载以上文件。

4. 继承关系对Context文件加载的影响, inheritLocations 的使用。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/base-context.xml"})
public class BaseTest {
// class body...
}

@ContextConfiguration(locations={"/extended-context.xml"})
public class ExtendedTest extends BaseTest {
// class body...
}


在以上代码中ExtendedTest会加载“/base-context.xml” 和“/extended-context.xml”两个文件,因为 inheritLocations 的默认值是true。

通过以上解释,我们可以看到Spring Context文件是基于classpath来定位的。在Eclipse下,classpath的设定往往和build环境下不同,怎么将build环境下的Context文件设定到@ContextConfiguration中呢?步骤如下: 点击Run->Run Configurations... 选择你要运行的测试用例的运行配置项,比如InContainerTests,然后点击User
Entries,然后点击Advanced,在弹出的窗口中选择Add External Folder,点击确定后可以选择任意目录。你可以基于Context文件相对于该目录的位置配置@ContextConfiguration中的参数。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: