java - Mock creation of Object inside method -
problem description
i'm trying mock object creation inside of method. have loginfragment
creating loginpresenterimpl
inside of oncreate
method, shown below:
public class loginfragment extends basefragment { private loginpresenter mpresenter; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mpresenter = new loginpresenterimpl(this); <<-- should mocked } }
i have problems combining robolectricgradletestrunner
, powermockrunner
in 1 test after reading this post, found way how that, test this:
baserobolectrictest.java
@runwith(powermockrunner.class) @powermockrunnerdelegate(robolectricgradletestrunner.class) @config(constants = buildconfig.class, sdk = 21) @powermockignore({"org.mockito.*", "org.robolectric.*", "android.*"}) public abstract class baserobolectrictest { }
test.java
@preparefortest({loginpresenterimpl.class}) public class test extends baserobolectrictest { private loginpresenterimpl mpresentermock; @rule public powermockrule rule = new powermockrule(); @before public void setup() { mockstatic(loginpresenterimpl.class); mpresentermock = powermockito.mock(loginpresenterimpl.class); } @test public void testing() throws exception { when(mpresentermock.loadusername(any(context.class))).thenreturn(valid_username); when(mpresentermock.loadpassword(any(context.class))).thenreturn(valid_password); when(mpresentermock.canautologin(valid_username, valid_password)).thenreturn(true); whennew(loginpresenterimpl.class).withanyarguments().thenreturn(mpresentermock); fragmenttestutil.startfragment(createloginfragment()); } private loginfragment createloginfragment() { loginfragment loginfragment = loginfragment.newinstance(); return loginfragment; } }
this bad code , opposite of "dependency injection" pattern.
if used dependency injection framework dagger
, such problem wouldn't happen used classed injected.
in test cases override modules provide mocks instead of real classes:
@module public class testdatamodule extends datamodule { public testdatamodule(application application) { super(application); } @override public databasemanager providedatabasemanager(databaseutil databaseutil) { return mock(databasemanager.class); } }
and mock behavior.
solid rules important in mainaining testable , reusable code.
Comments
Post a Comment