Error running unit from Chapter 11

I’m following Chapter 11: Testing of Server Side Swift with Vapor, Third Edition.

I’m getting this error on the unit test testGettingASingleUserFromTheAPI (page 159). No typos in the test itself and the other tests until this point in the chapter pass. Not sure what the problem is.

caught error: “typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [ModelCodingKey(stringValue: “name”, intValue: nil)], debugDescription: “Could not decode property”, underlyingError: Optional(Swift.DecodingError.keyNotFound(ModelCodingKey(stringValue: “name”, intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: “No value associated with key ModelCodingKey(stringValue: "name", intValue: nil) ("name").”, underlyingError: nil)))))”

failed - typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [ModelCodingKey(stringValue: “name”, intValue: nil)], debugDescription: “Could not decode property”, underlyingError: Optional(Swift.DecodingError.keyNotFound(ModelCodingKey(stringValue: “name”, intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: “No value associated with key ModelCodingKey(stringValue: "name", intValue: nil) ("name").”, underlyingError: nil)))))

Can you show the full test code and route handler?

The test

    let usersName = "Alice"
    let usersUsername = "alicea"
    let usersURI = "/api/users/"
    var app: Application!

    func testGettingASingleUserFromTheAPI() throws {
        let user = try User.create(name: usersName, username: usersUsername, on: app.db)

        try app.test(.GET, "\(usersURI)\(user.id!)", afterResponse: { response in
            let receivedUser = try response.content.decode(User.self)
            XCTAssertEqual(receivedUser.name, usersName)
            XCTAssertEqual(receivedUser.username, usersUsername)
            XCTAssertEqual(receivedUser.id, user.id)
        })
    }

Route handler

    func getHandler(_ req: Request) -> EventLoopFuture<User> {
        User.find(req.parameters.get("userID"), on: req.db)
            .unwrap(or: Abort(.notFound))
    }

The User model

final class User: Model, Content {
    static let schema = "users"

    @ID var id: UUID?
    
    @Field(key: "name") var name: String
    @Field(key: "username") var username: String
    @Children(for: \.$user) var drives: [Drive]
    @Children(for: \.$user) var clients: [Client]

    init() {}
    
    init(id: UUID? = nil, name: String, username: String) {
        self.name = name
        self.username = username
    }
}

I figured out my error. I had the wrong handler assigned to the get user route.

    func boot(routes: RoutesBuilder) throws {
        let userRoutes = routes.grouped("api", "users")
        userRoutes.get(":userID", use: getHandler)  // <--- I had the wrong handler function here. The unit test worked!