如何使用 ActivityTestCase 或 InstrumentationTestCase 测试异常
How to test Exceptions with ActivityTestCase or InstrumentationTestCase
我正在使用 Android Studio 1.2.2 创建一些 Junit 测试。这是我的测试类。它扩展自 ActivityTestCase(或 InstrumentationTestCase)。
public class TypeTest extends ActivityTestCase
{
TypesMeth typesMeth = new TypesMeth();
public void testTypes()
{
typesMeth.setValue((short) 1000000);
assertEquals(exception, typesMeth.getValue());
}
}
参数必须短。所以范围是从-32768到32767。
如果我传递 1000000 的值,它应该会抛出异常并且应该通过测试。
我该如何检查?类似于:assertExceptionIsThrown(true, typesMeth.getValue());
在经典的 JUnit 4 中,您会在测试用例之前添加一些注释
@Test(expected = IllegalArgumentException.class)
public void myUnitTest() {
...
}
据我所知,Android 中没有注释支持这一点,因此您需要使用 try 和 catch
以 JUnit 4 之前的方式进行
try {
doSomethingThatShouldThrow();
fail("Should have thrown Exception");
} catch (IllegalArgumentException e) {
// success
}
我正在使用 Android Studio 1.2.2 创建一些 Junit 测试。这是我的测试类。它扩展自 ActivityTestCase(或 InstrumentationTestCase)。
public class TypeTest extends ActivityTestCase
{
TypesMeth typesMeth = new TypesMeth();
public void testTypes()
{
typesMeth.setValue((short) 1000000);
assertEquals(exception, typesMeth.getValue());
}
}
参数必须短。所以范围是从-32768到32767。
如果我传递 1000000 的值,它应该会抛出异常并且应该通过测试。
我该如何检查?类似于:assertExceptionIsThrown(true, typesMeth.getValue());
在经典的 JUnit 4 中,您会在测试用例之前添加一些注释
@Test(expected = IllegalArgumentException.class)
public void myUnitTest() {
...
}
据我所知,Android 中没有注释支持这一点,因此您需要使用 try 和 catch
以 JUnit 4 之前的方式进行try {
doSomethingThatShouldThrow();
fail("Should have thrown Exception");
} catch (IllegalArgumentException e) {
// success
}