Vapor4.0写一些测试

没有文档的情况下,一切都靠摸索。刚开始的时候都不知道怎么下手,看看Vapor的测试怎么写,看看Fluent的测试怎么写。万事开头难,总算摸出个头绪。

首先,要配置测试环境, 在Xcode中的配置如下。

然后新建测试数据库。

1
2
3
docker run --name postgres-test -e POSTGRES_DB=test \
-e POSTGRES_USER=test -e POSTGRES_PASSWORD=test \
-p 5433:5432 -d postgres

测试一下:

1
2
3
4
5
6
7
8
9
func testDatabaseConfig() throws {
let app = Application(.testing)
defer { app.shutdown() }
try configure(app)
XCTAssertTrue(Int(Environment.get("DATABASE_PORT") ?? "5432")! == 5433, "DATABASE_PORT is wrong")
XCTAssertTrue(Environment.get("DATABASE_USERNAME") == "test", "DATABASE_USERNAME is wrong")
XCTAssertTrue(Environment.get("DATABASE_PASSWORD") == "test", "DATABASE_PASSWORD is wrong")
XCTAssertTrue(Environment.get("DATABASE_NAME") == "test", "DATABASE_PASSWORD is wrong")
}

测试新建表格是否成功:

1
2
3
4
5
6
7
8
9
10
11
12
13
func testArticleTable() throws {
let app = Application(.testing)
defer { app.shutdown() }
try configure(app)
let article = Article(name: "title", body: "body", categoryID: nil)
try article.save(on: app.db).wait()
let articles = try Article.query(on: app.db).all().wait()
XCTAssertEqual(articles.count, 1)
XCTAssertEqual(articles.first?.name, "title")
XCTAssertEqual(articles.first?.body, "body")
XCTAssertNil(articles.first?.category)

}

其中在configure.swift文件中加入一些辅助方法调用,使测试之前清空数据库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))

app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: Int(Environment.get("DATABASE_PORT") ?? "5432") ?? 5432,
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
database: Environment.get("DATABASE_NAME") ?? "vapor_database"
), as: .psql)

app.migrations.add(CreateArticleGategory())
app.migrations.add(CreateArticle())
//<==如果是测试环境,则清空数据库。注意这三行代码的位置要放在add方法之下的。
if app.environment == .testing {
try app.autoRevert().wait()
try app.autoMigrate().wait()
}

//开启页面渲染
app.views.use(.leaf)
app.leaf.cache.isEnabled = false
// register routes
try routes(app)
}