How to test assert throws exception in Android

how to write test case for catch (exception in junit)
junit assert exception
junit assert exception message
junit rule exception
android studio unit test exception
junit catch (exception test)
mockito.verify exception caught
mockito expected exception

is there a more elegant way to do an assert throws exception in Android then this?

public void testGetNonExistingKey() {   
        try {
            fail( );
        } catch (ElementNotFoundException e) {


Something like this does not work?!

    @Test(expected=ElementNotFoundException .class)

Thanks, Mark

Are you using a junit4 test runner? The @Test annotation won't work if you're running a junit3 test runner. Check the version that you're using.

Secondly, the recommended way to check for exceptions in your code is to use a Rule (introduced in junit 4.7).

public ExpectedException exception = ExpectedException.none();

public void throwsIllegalArgumentExceptionIfIconIsNull() {
    // do something

    exception.expectMessage("Icon is null, not a file, or doesn't exist.");
    new DigitalAssetManager(null, null);

You can continue to use the @Test(expected=IOException.class), but the above has the advantage that if an exception is thrown before the exception.expect is called, then the test will fail.

How do you assert that a certain exception is thrown in JUnit 4 tests , We can test expected exceptions using JUnit 5 assertThrows assertion. This JUnit assertion method returns the thrown exception, so we can use it to assert  You can continue to use the @Test(expected=IOException.class), but the above has the advantage that if an exception is thrown before the exception.expect is called, then the test will fail. Answer: I did something very similar to hopia’s answer with a couple of improvements.

I did something very similar to hopia's answer with a couple of improvements. I made it return the exception object so that you can check its message or any other properties, and I declared a Testable interface to replace Runnable because Runnable doesn't let your code under test throw checked exceptions.

public interface Testable {
    public void run() throws Exception;

public <T extends Exception> T assertThrows(
        final Class<T> expected, 
        final Testable codeUnderTest) throws Exception {
    T result = null;
    try {;
        fail("Expecting exception but none was thrown.");
    } catch(final Exception actual) {
        if (expected.isInstance(actual)) {
            result = expected.cast(actual);
        else {
            throw actual;
    return result;

Here's an example of calling it.

InvalidWordException ex = assertThrows(
    new Testable() {
        public void run() throws Exception {
            model.makeWord("FORG", player2);

        "FORG is not in the dictionary.", 

How to test that no exception is thrown?, is there a more elegant way to do an assert throws exception in Android then this​? public void testGetNonExistingKey() { try { alarm.getValue("NotExistingValue")  My preferred method for implementing this is to write a method called Throws, and use it just like any other Assert method. Unfortunately, .NET doesn’t allow you to write a static extension method, so you can’t use this method as if it actually belongs to the build in Assert class; just make another called MyAssert or something similar.

This is how I do it. I create a static method called assertThrowsException that takes in as arguments an expected exception class and a Runnable which contains the code under test.

import junit.framework.Assert;

public SpecialAsserts {
    public void assertThrowsException(final Class<? extends Exception> expected, final Runnable codeUnderTest) {
        try {
  "Expecting exception but none was thrown.");
        } catch(final Throwable result) {
            if (!expected.isInstance(result)) {
      "Exception was thrown was unexpected.");

This is the sample code to use the special assert in your test class (that extends AndroidTestCase or one of its derivatives):

public void testShouldThrowInvalidParameterException() {

    SpecialAsserts.assertThrowsException(InvalidParameterException.class, new Runnable() {
        public void run() {


Yes, there's a lot of work, but it's better than porting junit4 to android.

ExpectedException (JUnit API), Are you using junit4 test runner? @Test annotation will not work if you are using junit3 test runner. Check the version you are using. Secondly, the recommended​  We can use JUnit 4 @Test annotation expected attribute to define the expected exception thrown by the test method. @Test(expected = Exception.class) public void test() throws Exception { Foo foo = new Foo();; } JUnit 4 Assert Exception Message. If we want to test exception message, then we will have to use ExpectedException rule. Below is a complete example showing how to test exception as well as exception message.

If you're using Kotlin, you can take advantage of reified types to avoid passing the Exception subclass as an argument:

inline fun <reified T : Exception> assertThrows(runnable: () -> Any?) {
    try {
    } catch (e: Throwable) {
        if (e is T) {
        }"expected ${T::class.qualifiedName} but caught " +
            "${e::class.qualifiedName} instead")
    }"expected ${T::class.qualifiedName}")

fun exampleTest() {
    val a = arrayOf(1, 2, 3)
    assertThrows<IndexOutOfBoundsException> {

Use NUnit Assert.Throws method or ExpectedException attribute , And finally, if other than expected exception is thrown the test will fail but not with the assertion error as we would expect. For example, the following test: Test Exception in JUnit 5 - using assertThrows () method JUnit 5 provides the assertThrows () method that asserts a piece of code throws an exception of an expected type and returns the exception: assertThrows (Class<T> expectedType, Executable executable, String message)

With junit3 the following might help.

public static void assertThrows(Class<? extends Throwable> expected,
        Runnable runnable) {
    try {;
    } catch (Throwable t) {
        if (!expected.isInstance(t)) {
  "Unexpected Throwable thrown.");
    }"Expecting thrown Throwable but none thrown.");

public static void assertNoThrow(Runnable runnable) {
    try {;
    } catch (Throwable t) {"Throwable was unexpectedly thrown.");

JUnit Assert Exception - JUnit 5 and JUnit 4, Asserts that {@code runnable} throws an exception when invoked. If it does not, @Test public void testInvalidLike() { assertThrows(PrestoException.class,  Answers: Assert won’t work in Android because most of the time a person isn’t running in debug mode, but rather some optimized code. Thus, the proper solution is to manually throw an exception, with code like this: if (obj==null) throw new AssertionError ("Object cannot be null");

How to test assert throws exception in Android, @Test public void throwsExceptionWithSpecificType() the expected exception your test is successful when such an exception is thrown and it fails if a different  When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare we expect an exception to be thrown anywhere in the annotated test method. As a result, the test will fail if the specified exception isn't thrown when the test is run and will pass if it's thrown: 1 2

‍ How to test assert throws exception in Android, Unit tests are used to verify that a piece of code operates as the developer expects it to. Sometimes, that means checking that the code throws  Write code in the test class that will cause the trigger to ' addError ()'. b. Surround the above test class code with try - catch. c . Assert that an exception is thrown and that the exception message is the same one you created with ' addError ()'.

Exception testing, Example using @test(expected). Let's understand exception testing by creating a Java class with a method throwing an exception. You will  We can also configure Spy to throw an exception the same way we did with the mock: @Test(expected = NullPointerException.class) public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { MyDictionary dict = new MyDictionary(); MyDictionary spy = Mockito.spy(dict); when(spy.getMeaning(anyString())) .thenThrow(NullPointerException.class); spy.getMeaning("word"); }

  • Android is using a 3.x version of junit so it seems there is no other way - except to include junit4 and switch to this from the Android junit.
  • I just ran this with the junit:4.12 and figured that exception.expectMessage("Icon is null, not a file, or doesn't exist."); does not fail the test if expected message does not match.
  • I'm not sure assertThrowsException is quite right. The Throwable from the first will be caught and in the certain event it is not an instance of the intended exception class the next will fire.