Repository navigation
How to mock Entity Loader-type queries? (Or, examples on how to mock complex relationships?) #3239
|
Hi all, so, first question, is it even possible? Looking at the documentation I only see examples of mocking the results of simple edit: answer marked, thanks! tldr until/unless the developer experience for the mocking API improves a bit, you might be better off Not Doing That™ and just writing your own mocking layer for the unit tests where database logic is not the thing being tested. potentially a lot of boilerplate, but... so is using the mocking API as it is right now, with the upside of being less confusing to use. |
Replies: 2 comments 8 replies
|
yes but you need to mock each SQL result set rather than the final nested ModelEx Entity::load can execute several queries so queue their results in order with MockDatabase::append_query_results joined results need the column aliases selected by the query and collection results need the relation keys there are mocked load_one and load_many examples here share your SeaORM version and exact load chain and we can work out the fixtures |
|
I agree that the current Mock API doesn't offer a great developer experience. If you have more complex needs, you could look for other mocking solutions or implement your own. In fact, for complex relationships, I'd recommend integration or end-to-end tests rather than mocked unit tests. |
Yeah, although it's generally stable.
But if you don't rely too heavily on backend-specific features, you can use in-memory SQLite to speed up your tests.
While I don't think it would be difficult to refactor the mock implementation into an in-memory mock database, I don't see much point in doing so. If the goal is to test database behavior, the tests should run on a real database. If the database behavior isn't relevant and only data is needed, mocking the data access layer or repository would be more appropriate.
There are some good blog post on this topic:
https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html
https://abseil.io/resources/swe-book/html/ch13…