I have a quite complex Android project that I want to start testing quite thoroughly. So I implemented dependency injection to be able to test several components (I used Kodein for that). Then I started to write tests, and I found out that I have to use PowerMock, to mock calls to File.create for example. PowerMock can also mock constructors, factory methods, etc. So basically for testing I can achieve the same result of dependency injection, but without modifying the code.
So my question is: If I can mock anything with PowerMock, is there still a reason to implement dependency injection?
There are some cases you would use over one than the other, sometimes both. It all depends on what are you testing. Power Mock give you more control on what you can test or cant. While DI give you more direct result.
Here are some examples: Let's say if you have anonymous class.
@Override
public Query getQuery() {
Query q = Query.empty();
if (wp.minSpeed < 0)
q = Query.and(q, Query.eq(Speed.Function, WayPoint));
else {
q = Query.and(q, Query.eq(Speed.Function, Field));
q = Query.and(q, Query.eq(Speed.Calc, wp.maxSpeed-wp.minSpeed));
}
q = Query.and(q, Query.eq(Speed.Id, wp.altitude/greatCircle));
return q;
}
Since there is no way to test anonymous class to fulfill your 100% coverage. You should know that power mockito is the only way. You can only imitate the behavior of that class.
However, if you had some tedious class that has multiple classes calls you might want consider using dependency injection to reduce the number of spy / mocking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With