Unit testing - creating service classes with Depends #15266
-
First Check
Commit to Help
Example Codeclass House:
def __init__(
self,
kitchen: Annotated[Kitchen, Depends()],
):
self._kitchen = kitchen
@router.post("/house")
async def house(
house: Annotated[House, Depends()],
request: Request,
) -> None:
house.process(request)DescriptionDepends allows automatic injection of classes in API endpoints, including their dependencies, which is very useful. To test, we can use However, what if we want to write Pytest unit tests of just the service class? Does FastAPI Depends provide a way to inject the service class directly into the test class / function? It's not ideal to have to manually construct the object and its deps for unit tests. Operating SystemLinux, Windows, macOS Operating System DetailsNo response FastAPI Version0.128.0 Pydantic Version2.12.5 Python Version3.12 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
No, |
Beta Was this translation helpful? Give feedback.
No,
Dependswill not work when you instantiateHousemanually. And there is no official way to achieve this (to make it resolve dependencies automatically).In this case you need to pass the value for
kitchenparameter explicitly