C
C#2y 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
...
@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
...
2 Replies
Doctor
DoctorOP2y ago
xUnit has class fixtures but if I undersand correctly there's no way to inject one fixture into another, for example by specifying it as a dependency in constructor:
public class UserFixture
{
public User User;
public UserFixture()
{
// Create user
}
}

public class UserClientFixture
{
public HttpClient HttpClient;
public UserClientFixture(
UserFixture userFixture
)
{
HttpClient = ...; // Create http client using userFixture
}
}
public class UserFixture
{
public User User;
public UserFixture()
{
// Create user
}
}

public class UserClientFixture
{
public HttpClient HttpClient;
public UserClientFixture(
UserFixture userFixture
)
{
HttpClient = ...; // Create http client using userFixture
}
}
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server