在shell执行时,JUnit测试的ComparisonFailure

时间:2017-06-27 13:35:10

标签: java android android-studio junit

对于以下课程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;
    }

}

...和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;
}

...我写了这个单元测试:

@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();
    }

}

测试在Android Studio 2.1.3中成功,但在我的计算机上运行./gradlew clean test时,失败(MacOS 10.11.6,El Capitain,Java 1.7.0_79)。这是错误输出:

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)

相关帖子

1 个答案:

答案 0 :(得分:2)

你如何模仿TextUtils?使用默认的Android测试存根时,部分TextUtils.isEmpty(text.getValue())应始终为false

请务必使用合适的实现,或者考虑使用一些您可能已经提供的其他依赖项的字符串实用程序。

由JJD编辑

你是对的,谢谢!我使用Unmock plugin。所以我必须取消模拟相关的包,以在单元测试中公开TextUtils

unMock {
    keepStartingWith "android.text."
}