当前位置:  开发笔记 > 编程语言 > 正文

我们可以使用JUNIT进行自动集成测试吗?

如何解决《我们可以使用JUNIT进行自动集成测试吗?》经验,为你挑选了3个好方法。

您如何自动化集成测试?我使用JUnit进行其中一些测试.这是解决方案之一还是完全错误的?你有什么建议?



1> Johannes Bro..:

我已经使用JUnit进行了大量的集成测试.当然,集成测试可能意味着许多不同的事情.对于更多系统级集成测试,我更喜欢让脚本从外部驱动我的测试过程.

这是一种适用于使用http和数据库的应用程序的方法,我想验证整个堆栈:

    使用Hypersonic or H2的内存模式作为数据库更换(本最适合的ORM)

    初始化数据库@BeforeSuite或等效(再次:最简单的ORM)

    使用Jetty启动进程内Web服务器.

    @Before 每次测试,清除数据库并用必要的数据初始化

    用于JWebUnit对Jetty执行HTTP请求

这为您提供了集成测试,无需任何数据库或应用程序服务器设置即可运行,并且可以从http向下运行堆栈.由于它不依赖于外部资源,因此该测试在构建服务器上运行良好.

这里使用的一些代码:

@BeforeClass
public static void startServer() throws Exception {
    System.setProperty("hibernate.hbm2ddl.auto", "create");
    System.setProperty("hibernate.dialect", "...");
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setJdbcUrl("jdbc:hsqldb:mem:mytest");
    new org.mortbay.jetty.plus.naming.Resource(
             "jdbc/primaryDs", dataSource);


    Server server = new Server(0);
    WebAppContext webAppContext = new WebAppContext("src/main/webapp", "/");
    server.addHandler(webAppContext);
    server.start();
    webServerPort = server.getConnectors()[0].getLocalPort();
}

// From JWebUnit
private WebTestCase tester = new WebTestCase();

@Before
public void createTestContext() {
    tester.getTestContext().setBaseUrl("http://localhost:" + webServerPort + "/");
    dao.deleteAll(dao.find(Product.class));
    dao.flushChanges();
}

@Test
public void createNewProduct() throws Exception {
    String productName = uniqueName("product");
    int price = 54222;

    tester.beginAt("/products/new.html");
    tester.setTextField("productName", productName);
    tester.setTextField("price", Integer.toString(price));
    tester.submit("Create");

    Collection products = dao.find(Product.class);
    assertEquals(1, products.size());
    Product product = products.iterator().next();
    assertEquals(productName, product.getProductName());
    assertEquals(price, product.getPrice());
}

对于那些想要了解更多信息的人,我在Java.net上写了一篇关于Jetty和JWebUnit的嵌入式集成测试的文章.



2> Robin..:

JUnit有效.没有限制将其限制为仅进行单元测试.我们使用JUnit,Maven和CruiseControl来进行CI.

可能存在特定于集成测试的工具,但我认为它们的有用性取决于您正在集成的系统组件类型.JUnit适用于非UI类型测试.



3> sblundy..:

当使用Maven构建项目时,我对TestNG有了更多的运气,因为它具有@BeforeSuite@AfterSuite操作.这是有用的,因为如果任何集成测试失败,Maven将不会执行'post-integration-test`.Ant没有问题,所以我只是偏爱使用jUnit.

在任何一种情况下,将测试分割为TestNG和jUnit都有助于集成测试.

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有