Problem Description
I'm trying to mock object creation inside of method.
I have LoginFragment
which is creating LoginPresenterImpl
inside of onCreate
method, like shown below:
public class LoginFragment extends BaseFragment {
private LoginPresenter mPresenter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPresenter = new LoginPresenterImpl(this); <<-- Should be mocked
}
}
I have some problems with combining RobolectricGradleTestRunner
and PowerMockRunner
in one test but after reading this post, I found way how to do that, so my test look like 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;
}
}