1

For the following classes Texts ...

import android.support.annotation.NonNull;
import android.text.TextUtils;    
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Collections;
import java.util.List;
import hrisey.Parcelable;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Parcelable
public final class Texts implements android.os.Parcelable {

    @NonNull List<Text> texts = Collections.emptyList();

    public boolean hasTexts() {
        return !texts.isEmpty() && textsHaveValues();
    }

    private boolean textsHaveValues() {
        for (Text text : texts) {
            if (TextUtils.isEmpty(text.getValue())) {
                return false;
            }
        }
        return true;
    }

}

... and Text ...

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import hrisey.Parcelable;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Parcelable
public final class Text implements android.os.Parcelable {

    private String textKey;
    private String value;
}

... I wrote this unit test:

@RunWith(JUnit4.class)
public class TextsTest {

    private Texts texts;

    @Before
    public void setUp() {
        texts = new Texts();
    }

    @Test
    public void hasTextsWithSingleEmptyItem() throws Exception {
        texts.setTexts(Collections.singletonList(new Text()));
        assertThat(texts.hasTexts()).isFalse();
    }

}

The test succeeds in Android Studio 2.1.3 but it fails when I run ./gradlew clean test on my machine (MacOS 10.11.6, El Capitain, Java 1.7.0_79). Here is the error output:

com.example.model.TextsTest > hasTextsWithSingleEmptyItem FAILED
    org.junit.ComparisonFailure: expected:<[fals]e> but was:<[tru]e>
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(
    NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
    DelegatingConstructorAccessorImpl.java:45)
        at com.example.model.TextsTest.hasTextsWithSingleEmptyItem(TextsTest.java:31)

Related posts

JJD
  • 50,076
  • 60
  • 203
  • 339

1 Answers1

2

How do you mock TextUtils? The part TextUtils.isEmpty(text.getValue()) should always be false when using the default Android test stubs.

Be sure to use a suitable implementation or consider using a different set of string utilities you already might have available with some other dependencies.

Edit by JJD

You are right, thanks! I use the Unmock plugin. So I had to unmock the relevant package to expose TextUtils in the unit tests:

unMock {
    keepStartingWith "android.text."
}
JJD
  • 50,076
  • 60
  • 203
  • 339
tynn
  • 38,113
  • 8
  • 108
  • 143