Patterns.EMAIL_ADDRESS returns null - android

#RunWith(MockitoJUnitRunner.Silent.class)
public class LoginActivityTest {
#InjectMocks
LoginActivity loginActivity;
private Pattern emailPattern;
#Before
public void createLogin(){
this.emailPattern = Patterns.EMAIL_ADDRESS;
}
#Test
public void checkValidation(){
mock(LoginActivity.class);
UserVO userVO = new UserVO();
userVO.setEmailID("invalid");
userVO.setPassword("a");
boolean b = loginActivity.validatesFields(userVO);
assertFalse(b);
}
}
this.emailPattern = Patterns.EMAIL_ADDRESS; This is creating null pointer object in MockitoJunitTestClass. But, when I run this on Activity it gets initialized properly.

Use PatternsCompat instead of Patterns

I was having a similar problem because it was just a simple test, but when I added #RunWith(AndroidJUnit4::class) the problem was fixed. Check if this is test that must run with Android resources or not.

I am a little confuse with your test:
You are mocking LoginActivity.class but not setting anything with that. I believe you want to do something like loginActivity = mock(LoginActivity.class); instead.
Also, your are mocking instead spying the class, so it won't access the real method in order to verify the flow of this method. In other words, your test is doing nothing in fact.
Finally, this emailPattern is never used on your test (probably it is used on you code), so I believe you want to mock it (I am supposing it). What I recommend you do is something like this:
#RunWith(MockitoJUnitRunner.Silent.class)
public class LoginActivityTest {
#Spy
#InjectMocks
private LoginActivity loginActivity;
#Mock
private OtherStuff otherStuff;
#Test
public void checkValidation(){
UserVO userVO = new UserVO();
userVO.setEmailID("invalid");
userVO.setPassword("a");
doReturn(Patterns.EMAIL_ADDRESS).when(otherStuff).doStuff();
boolean result = loginActivity.validatesFields(userVO);
assertFalse(result);
}
}
What I did here is just an example of unit test which is validating what validateFields() is doing. I suppose that inside this method you have some method on, what I name otherStuff, which calls a method that returns Patterns.EMAIL_ADDRESS, which is what you want to mock.
It would be really better if you insert the LoginActivity code to be more precise here, but I hope I helped you.

Related

Why is Mockito boolean stub being ignored

I have a method that checks a condition and does some work.
public void doSomeWork(){
if(!UtilityClass.someCondition()){
context.getmeSomething();
}
}
My test looks like this.
#Test
public void test(){
myClass.doSomeWork();
PowerMockito.verifyStatic(UtilityClass.class)
when(UtilityClass.someCondition()).thenReturn(false);
verify(mContext, times(1)).getmeSomething();
}
The problem is the stub is simply ignored. The test passes regardless of the stub result. By the same token, never verification on fails and I get Never wanted at the test but wanted at my class under test from Mockito. My question is why the boolean stub being ignored?
Update
I am not sure if it is significant with my original question, but the Utility class is included in the prepare for test and has mockStatic call in setUp.
Ordering of your statements!
Register your mocks and behaviour of it.
Call the method
Verify
EDIT:
you should also make sure, that UtilityClass is a mock. You can't stub actual classes, just mocks of them.
#Rule
public MockitoRule rule = MockitoJUnit.rule();
#Mock
private UtilityClass utilityClassMock;
private MyClass myClass;
#Before
public void beforeEachTest() {
myClass = new MyClass(utilityClassMock);
}
#Test
public void test(){
when(utilityClassMock.someCondition).thenReturn(false);
myClass.doSomeWork();
verify(mContext, times(1)).getmeSomething();
}
Just like GabrielJoerg said the stubbing should happen first before the method call. But the real issue here is that when stubbing, you should avoid calling verifyStatic. Here is what worked for me.
#Test
public void test(){
when(UtilityClass.someCondition()).thenReturn(false);
myClass.doSomeWork();
verify(mContext, times(1)).getmeSomething();
}

How to test void method with Mockito's doAnswer

I am new to Mockito and trying to understand how to use doAnswer in order to test a void method.
Here's my class with the onDestroy method to test:
public class TPresenter implements TContract.Presenter {
private CompositeSubscription viewSubscription;
//.......
#Override public void onCreate(.......) {
this.viewSubscription = new CompositeSubscription();
//.......
}
#Override public void onDestroy() {
if(viewSubscription != null && !viewSubscription.isUnsubscribed()) {
viewSubscription.unsubscribe();
}
}
Now I want to write a test for onDestroy() namely to verify that after executing onDestroy the subscription is unsubscribed. I found several examples to use doAnswer for testing void methods, for example here, and also here but I do not understand them.
Please show how to test the method onDestroy.
The normal way how you could test your onDestroy() would be based on viewSubscription being a mocked object. And then you would do something like:
#Test
public testOnDestroyWithoutUnsubscribe() {
when(mockedSubscription.isUnsubscribed()).thenReturn(false);
//... trigger onDestroy()
verifyNoMoreInteractions(mockedSubscription);
}
#Test
public testOnDestroyWithUnsubscribe() {
when(mockedSubscription.isUnsubscribed()).thenReturn(true);
//... trigger onDestroy()
verify
verify(mockedSubscription, times(1)).unsubscribe();
}
In other words: you create a mocked object, and you configure it to take both paths that are possible. Then you verify that the expected actions took place (or not, that is what the first test case does: ensure you do not unsubscribe).
Of course, you can't test the "subscription object is null" case (besides making it null, and ensuring that no NPE gets thrown when triggering the onDestroy()!
Given the comment by the OP: one doesn't necessarily have to use mocking here. But when you want to test a void method, your options are pretty limited. You have to observe side effects somehow!
If you can get a non-mocked viewSubscription instance to do that, fine, then do that. But if not, then somehow inserting a mocked instance is your next best choice. How to do the "dependency injection" depends on the exact context, such as the mocking/testing frameworks you are using.
Testing void methods in your main class under test is not a problem as does not require doAnswer.
Here is an example of how could you go about testing the call to unsubscribe.
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class TPresenterTest {
#InjectMocks
private TPresenter target = new TPresenter();
#Mock
private CompositeSubscription viewSubscription;
#Test
public void onDestroyShouldUnsubscribeWhenSubscriptionNotNullAndUnsubscribed() {
when(viewSubscription.isUnsubscribed()).thenReturn(false);
target.onDestroy();
verify(viewSubscription).unsubscribe();
}
#Test
public void onDestroyShouldNotUnsubscribeWhenSubscriptionNotNullAndNotUnsubscribed() {
when(viewSubscription.isUnsubscribed()).thenReturn(true);
target.onDestroy();
verify(viewSubscription, never()).unsubscribe();
}
}
As I mentioned in my comment to #GhostCat 's answer, my example is in fact un-testable because of the "new" instance of CompositeSubscription class. I would have to re-factor it and #GhostCat 's comment to his/her answer shows a way to do it.

How to test new Button()?

I have some ButtonCreator.class that create Android UI element via models. Have any ideas how to test it?
public class ButtonCreator {
Button createWidget(ButtonComponent buttonComponent, Context context) {
Button button = new Button(context);
button.setText(buttonComponent.getText());
return button;
}
}
I wrote a test:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Button.class, Context.class, ButtonCreator.class})
public class CreaterButtonTest {
#Mock
Context mContext;
#Mock
Button mButton;
#Test
public void createWidget() {
PowerMockito.whenNew(Button.class).withAnyArguments(). thenReturn(mButton);
ButtonCreator buttonCreator = new ButtonCreator();
ButtonComponent buttonComponent = new ButtonComponent();
buttonComponent.setText("someText");
Button buttonActual = buttonCreator.createWidget(buttonComponent, mContext);
assertThat(buttonActual.getText(), is("someText"));
}
}
But in buttonActual.getText() I have a null. Help it solve please.
Important thing to understand about mocks, is that they will never function as your original object, unless you specify the behavior.
In your case:
The Mocked button will receive the call of setText(), but because it's a Mocked object, it does not have any internal state to store the text string, so it will correctly return null.
You can specify the behavior to return a string with something like:
when(mButton.getText()).thenReturn("mytext");
But this is not so optional, because in the end you are testing how the mock framework is working.
In these cases, you should use the verify method. Every mock object records all method calls during it's lifetime.
verify(mButton, times(1)).setText("someText"));
With this you are making sure that the exact method calls are happening.

How to mock and verify a callback in method using Mockito

Within this method, I want to mock and ensure that mSharedPrefsManager gets called when I don't pass in a certain email string.
#Override
public void retrieveWithEmail(final String email, final WelcomeContract.Presenter presenter)
{
retrieveInteractor.buildRetrieveRequest(email, new RetrieveImpl.OnRetrieveCompletedListener()
{
#Override
public void onRetrieveCompleted(final MaitreBaseGson retrieveResponse, RetrieveImpl retrieveClass)
{
if (retrieveResponse.getStatus().equals(mContext.getString(R.string.ok)))
{
if (!email.equals("certain#email.com"))
mSharedPrefsManager.storePoints(Integer.parseInt(retrieveResponse.getData().getPoints()));
presenter.updateSilhouette(retrieveResponse);
}
// Silently swallow failures
}
});
}
However, with my test I'm not able to catch whether mSharedPrefsManager is called. Mockito says that .storePoints() is never called. I thought about doing a doReturn().when() but as this is within the method that wouldn't work, would it?
How do I catch the interactions on sharedPrefsManager?
Mockito also says that .updateSilhouette() is not called. Do I need to mock onRetrieveCompleted() somehow?
#RunWith(MockitoJUnitRunner.class)
public class WelcomeInteractorTest
{
#Mock
RetrieveImpl retrieveInteractor;
#Mock
WelcomePresenter welcomePresenter;
#Mock
SharedPrefsManager sharedPrefsManager;
#Mock
Context context;
#InjectMocks WelcomeInteractorImpl welcomeInteractor;
#Mock
RetrieveImpl.OnRetrieveCompletedListener onRetrieveCompletedListener;
#Test
public void RetrieveWithCertainEmail_SavePoints()
{
welcomeInteractor.retrieveWithEmail("certain#email.com", welcomePresenter);
verify(retrieveInteractor).buildRetrieveRequest(eq("certain#email.com"), any(RetrieveImpl.OnRetrieveCompletedListener.class));
verify(sharedPrefsManager).storePoints(any(Integer.class));
verify(welcomePresenter).updateSilhouette(any(MaitreBaseGson.class));
}
}
Attempting to use #Spy caused a lot of issues for me as RetrieveImpl interacts with a network.
I instead used a Captor and captured the callback.
#Captor
private ArgumentCaptor<RetrieveImpl.OnRetrieveCompletedListener> mOnRetrieveCompletedListenerCaptor;
...
#Test
public void isTest()
{
...
verify(retrieveInteractor).buildRetrieveRequest(eq(email), mOnRetrieveCompletedListenerCaptor.capture());
mOnRetrieveCompletedListenerCaptor.getValue().onRetrieveCompleted(mockMaitreBaseGsonSuccessful, retrieveInteractor);
}
You are mocking:
#Mock
RetrieveImpl retrieveInteractor;
This means that when you call retrieveInteractor.buildRetrieveRequest(..), the real implementation is not invoked and eventually the methods that you expect to be called within that method call are never called..
Try using #Spy instead, this will actually allow for the real implementation to be called and you can verify that object also:
#Spy
RetrieveImpl retrieveInteractor;
Just one the side.. in think you are testing too much there and going to deep in your verifications.
That test in my opinion should be done for the RetrieveImpl.OnRetrieveCompletedListener class. Not the one that is in your question.
But thats just to my taste..

Cannot access MyApplication members from Mockito

This is my code:
#Mock
MyApplication application;
#Before
public void setup() {
application = Mockito.mock(MyApplication .class);
}
#Test
public void createProducts() {
application.ormLiteDatabaseHelper.getProductDao().create(new Product());
}
I get a NullPointerException at this line. My Application class inits the OrmLiteDatabaseHelper in its onCreate, how do I access the ormLiteDatabaseHelper from the mocked version of MyApplication?
application is a "mock" object. It only pretents to be a "MyApplication". Thus the only thing it can return for the method ormLiteDatabaseHelper is null and thus calling getProductDao on that will fail with a NullPointerException.
If you want it to return anything, then you need to tell your mock that, for example by...
OrmLiteDatabaseHelper ormLiteDatabaseHelper = ..something...;
Mockito.when( application.ormLiteDatabaseHelper ).thenReturn ( ormLiteDatabaseHelper);
Only then will your mock know to return something else than null. Of course, there are other ways, but for starters... Perhaps you also need partial mocking, which would be explained here, but without further info, it's hard to say.
Also, if you write #Mock, then you should either use the correct #RunWith annotation or call MockitoAnnotations.initMocks(this); instead of creating the mock manually via Mockito.mock. If you want to use the later, you don't need the #Mock annotation.

Categories

Resources