C#C
C#4y ago
Doctor

❔ Using fixtures in xUnit

I've been trying to create some tests for my web application using xUnit (I've just started looking into C# recently, but I mainly use Python)
I wonder if there's a way to "nest" fixtures or use then in each other, for example I can create user in database and then create http client authenticated for that specific user
Here's an example in python + pytest:
@pytest.fixture
async def user(session: AsyncSession) -> User:
    # Session here is another fixture, it works the same as DbContext in EF Core
    user = User(...)
    session.add(user)
    await session.flush()
    return user


@pytest.fixture
async def user_http_client(fastapi_app: ASGIApp, user: User) -> httpx.AsyncClient:
    async with httpx.AsyncClient(
        app=fastapi_app,
        headers={"Authorization": "Get token somehow using user"},
    ) as client:
        yield client


async def test_get_me(user_http_client: httpx.AsyncClient) -> None:
    response = await user_http_client.get("/users/me")
    assert response.status_code == status.HTTP_200_OK
    ...
Was this page helpful?