gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:49:47 25 4
gpt4 key购买 nike

如何实现自动化 integration testing ?我使用 JUnit 进行其中一些测试。这是解决方案之一还是完全错误?你有什么建议?

最佳答案

我使用 JUnit 进行了很多集成测试。当然,集成测试可能意味着许多不同的东西。对于更多的系统级集成测试,我更喜欢让脚本从外部驱动我的测试过程。

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

  1. 在内存模式中使用 Hypersonic 或 H2 作为数据库的替代品(这对 ORM 最有效)
  2. @BeforeSuite 或等效项中初始化数据库(同样:使用 ORM 最简单)
  3. 使用 Jetty 启动进程内 Web 服务器。
  4. @Before 每次测试,清空数据库并用必要的数据进行初始化
  5. 使用 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<Product> products = dao.find(Product.class);
assertEquals(1, products.size());
Product product = products.iterator().next();
assertEquals(productName, product.getProductName());
assertEquals(price, product.getPrice());
}

对于那些想了解更多的人,我写了 article about Embedded Integration Tests with Jetty and JWebUnit在 Java.net 上。

关于java - 我们可以使用 JUNIT 进行自动化集成测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/284774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com