I have a variable that I'm initializing with `val ...
# announcements
d
I have a variable that I'm initializing with
val something: Something by lazy {}
but for unit testing I need to be able to mock retrofit. I'd also prefer that the code for building the Retrofit be encapsulated in the class itself. I have a few ideas but I'd like the Kotlin idiomatic way of doing it.
The main way I was thinking of doing it was having 2 constructors.
But for some reason, this seems more Java-like than Kotlin-like.
a
How about having an interface that handles API calls ? You can have an implementation with Retrofit, and a Mock one
d
In a sense, I have that too. Retrofit may have been too specific of an example. Though; now I'm rethinking my testing strategy.
c
with mockk you can mock properties.
d
So in the following case;
something
can be mocked by Mockk?
(typing code)
Untitled
And the test Mock can work like ...
Untitled
And the lazy lambda won't be called?
s
Is
Thing
a class, abstract class, or interface?
d
Class
s
Your snippet says that subsequent calls of
thing.something
will always return the string
"test string"
Also since your return is not computed, you should just use
Copy code
every  { thing.something } returns "test string"
d
Yeah, makes sense. It would be computed tho, not just literal. 😉
s
FWIW in your original question, iircc with Retrofit you define an interface for your remote API anyways, so you should just mock that interface so you decouple yourself from any implementation of that API.
d
That's why I took away Retrofit as the example. I will have tests for mocking the interfaces but I also need to test a few things that go into the retrofit builder.
I just want to make sure I can mock the various pieces that are involved.