Question about testing ktor. Has anyone had luck m...
# server
f
Question about testing ktor. Has anyone had luck mocking an ApplicationRequest? I'd like to be able to write unit tests without the whole test server harness, which has been fine for integration testing but a bit much for unit tests. Specifically, I just want to test a function that parses a request, so I just want to pass my function a test request without having to make a call to the test server to get one
t
I don’t use ktor, but the advice remains the same for any code - “don’t mock what you don’t own”. Is
ApplicationRequest
an object you can construct?
f
Technically, yes, but it's a huge pain to construct. Using the test harness is the easiest way to, and that's what I'm trying to move away from
Maybe there's some way I could hack a request out of the test harness as part of a before test step? Sounds dirty
t
How about introducing your own abstraction layer to only expose the parts you want? You could create an interface to expose the data you’re interested in in your code under test, then for production it’s a simple wrapper around
ApplicationRequest
to forward the values.
tbh though, when it comes to HTTP level stuff, I’ve found that having as close to the real server as possible avoids any misunderstanding about how requests might work
💯 1
f
Right, I definitely still want the request level integration tests; I just also want to be able to unit test everything within the request that doesn't need to know about ktor
I'll probably just need to write some test utils to mitigate the boilerplate. If I can't get around having to use the test harness, I can at least hide it a little 😛
t
If you have integration level tests covering your behaviour, do you need the unit tests?
f
It's easier to test more cases with unit testing. It becomes very cumbersome with integration tests and because of the excess setup tends to obfuscate what is actually being tested
t
Agree on the first, the second can be mitigated though
And applies to any test really
f
True, I can always use some test utils to move setup out of the tests themselves, but then I still have more code to maintain and too many test utils like this can make the tests brittle to change and sometimes lead to false positives if you aren't careful so I try to avoid indirection whenever possible in tests and keep it very dumb.
I think I can up with something lightweight enough for my purposes. This is sort of a special case anyway; most of the time I won't be testing functions operating on a request
d
You can also try #http4k 😅 (hides)
👀 1
🙂 1
💯 3
2
f
http4k looks really nice, and the service I'm working is new and small enough to give it a spin without much extra effort - thanks for the rec!