Hi guys, I am using `nhaarman/mockito-kotlin`and I...
# test
r
Hi guys, I am using `nhaarman/mockito-kotlin`and I am trying to mock my API class which has a dependency injection. Something like this:
Copy code
class Api(s: String) {
 private val name = s
}
I am doing this:
_val apiMock = mock_<Api> { … }
How can I pass the `s`argument the class needs? Thanks in advance
t
I think I must be missing something. If it’s mocked it doesn’t need the
s
argument
r
I am still a beginner on tests so probably I misunderstood the way this works 😅
t
the mock is used in the place of your
Api
class, so any argument that
Api
takes in the constructor are no longer required
its a tough concept to get your head around when you start
r
Yes, I found out that I actually wanted to use
spy
instead of
mock
. This way I can pass an instance instead of a class
t
This is just my opinion (but it’s right!) - you shouldn’t do that unless you have absolutely no choice. You should wrap up the functionality you want behind an interface and mock that. If you don’t own the class, a create a thin wrapper around the actual code that can implement your interface and use delegation.
r
hmm ok, I will have a deeper look into it 🙂 thanks
t
If you’re interested - here is a (short) book on testing I wrote a few years back - freely available now https://github.com/tddmonkey/tests-need-love-too/blob/master/tests-need-love-too-ebook.pdf
r
Thank you
m
To expand on what Colin said, testing should be about testing the contract the API/interface provides. And not about testing every little bit of the inplementation. Tests are more about facilitating refactoring, determining if the interface is 'pleasant' to use, and ensuring it continues to do what it says it will. If you have good tests, you can change the implementation (but not the outcome, so a true refactoring) of your service and not have to touch the tests. If you have to touch the tests even though the functionality hasn't changed, then you most likely have your tests too tightly coupled to your implementation details or your implementation could be improved.
r
Thanks Mike, now I understand your point. In fact is my implementation that can be improved in order to use the mocks correctly.
t
This is what introducing an interface should help you do. It’s the “I” in SOLID principles. Ideally you want to aim for laser-focussed interfaces providing the collaboration points. You can still have a single class to implement those interfaces tho
r
Understood 🙂