我做错了什么? Android JUnit

时间:2016-05-30 17:56:17

标签: java android junit

我想要稳健的junit。并创建一些测试应用程序,然后尝试测试。我有简单的活动,在这个活动中我有方法checkEditText这个方法返回true或false。这是我的活动:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}

public boolean checkEditText(int number) {
        return number > 0 ? true : false;

    }

这是测试:

package ac.junit2;


import android.test.ActivityInstrumentationTestCase2;

import org.junit.Assert;

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    public MainActivityTest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        MainActivity activity = getActivity();
        Assert.assertNotNull(activity);
    }



    public void testCheckNumber() {
        MainActivity activity = getActivity();

        boolean action = activity.checkEditText(0);
        assertTrue(action);
    }


}

我有错误:

java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)
    at org.junit.Assert.assertNotNull(Assert.java:712)
    at org.junit.Assert.assertNotNull(Assert.java:722)
    at ac.junit2.MainActivityTest.setUp(MainActivityTest.java:26)
    at junit.framework.TestCase.runBare(TestCase.java:139)
    at junit.framework.TestResult$1.protect(TestResult.java:122)
    at junit.framework.TestResult.runProtected(TestResult.java:142)
    at junit.framework.TestResult.run(TestResult.java:125)
    at junit.framework.TestCase.run(TestCase.java:129)
    at junit.framework.TestSuite.runTest(TestSuite.java:252)
    at junit.framework.TestSuite.run(TestSuite.java:247)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

2 个答案:

答案 0 :(得分:1)

因为0不大于0.所以

return number > 0 ? true : false;
当数字为0时,

将返回false。

在测试中,您声明为true但结果为false。

答案 1 :(得分:1)

测试失败了,就像你编程一样。 activity.checkEditText(0);的结果是false,因为您定义了返回false的方法,除非参数更大大于0.然后在您的测试中,您声明结果应为true