Live data from Hacker News

Ask HN: Best Way to Mock APIs in 2020?

news.ycombinator.com

61–63 of 63 posts

Re: Ask HN: Best Way to Mock APIs in 2020?

#61
post #12

Can someone explain to me what this is all about? Shouldn't you hide all your API calls behind an interface, and then mock that interface? Dependency inversion principle, depend upon abstractions and all that.

What does mocking an interface mean, like a mock implementation? How is that different then defining an API and then having stub methods on the front returning pretend data?

I think they mean wrapping the REST api in a class (aka "data provider" or "repository pattern") this way you've abstracted the HTTP request logic away from your application.

Both the API and the Mock implementation will require the same interface.

Re: Ask HN: Best Way to Mock APIs in 2020?

#62
post #39
post #12

Can someone explain to me what this is all about? Shouldn't you hide all your API calls behind an interface, and then mock that interface? Dependency inversion principle, depend upon abstractions and all that.

I've gone through this process a few times: 1) Join a project and fume about how they didn't write nice, clean, "testable" code. 2) Build some sort of integration testing framework that also mocks out REST API calls relatively cheaply (e.g. using recording/playback against a live system). 3) Realize that I can now refactor the code such that it is nice, clean and more easily "unit testable". 4) Realize that with an e…

Totally agree with you. I think the industry is going through an "emperor has no clothes" thing with unit tests and dependency inversion at the moment.

The creator of BDD gave this talk a few years ago, which resonated with me: https://www.youtube.com/watch?v=4Y0tOi7QWqM

> it occurred to me that it would actually be kind of great to write tests where the entire implementation including the language itself could be swapped out without really changing the tests.

This is exactly what I've been doing and advocating for for a while. Don't mock things like databases at all in your code. If you want to use a mock, use a "first class" mock like https://cloud.google.com/bigtable/docs/emulator.

The other thing is that TDD was born in a world where containers aren't the norm. All the pain of higher level testing really comes up from setting up an appropriate environment. If you're already using Docker or k8s, that pain is pretty much 0.

Post reply on HN