admin管理员组

文章数量:1125736

I have a FastAPI web service using the Controller-Service-Repository pattern. I'm wondering about the best approach for implementing unit tests.

Here's my current code structure:

[Model]

class UserInfo(SQLModel, table=True):
    __tablename__ = 'user_info'
    __table_args__ = {'schema': 'Auth'}
    id: int | None = Field(default=None, primary_key=True)
    name: str = Field(nullable=False)
    username: str = Field(nullable=False)
    email: str = Field(nullable=False)
    role: str = Field(nullable=False)
    tenant_id: int = Field(nullable=False)
    activate: bool = Field(nullable=False)

[Repository]

def get_user_info_repository(tenant_id: str) -> list[UserInfo]:
    with Session(engine) as session:
        statement = select(UserInfo).where(UserInfo.tenant_id == tenant_id)
        result = session.exec(statement)
        return result.all()

[Service]

def get_user_info_service(tenant_id: str) -> list[UserInfo]:
    user_list = get_user_info_repository(tenant_id)
    return user_list

[Schema]

class UserResponse(SQLModel):
    username: str
    name: str
    email: str
    role: str
    tenant_id: str
    activate: bool
    
class UserInfoResponse(SQLModel):
    user_limit: int
    users: list[UserResponse]

[Controller]

@app.get("/user_info", response_model=UserInfoResponse)
def user_info():
    response = get_user_info_service("Test_Account")
    return UserInfoResponse(users=response)

My questions are:

  1. Should I write unit tests for each layer (Controller, Service, Repository) and mock their dependencies? Or is it sufficient to just test the Controller layer using TestClient?
  2. Should unit tests include or avoid cross-layer testing scenarios? (For example, should I test Controller+Service together or always test them separately?)
  3. Since my Service layer is just passing through data without any business logic, should I still write unit test case for it?

本文标签: