Code Poet
Code Poet

Reputation: 11437

Are asserts available on Android?

Are asserts available on Android? I have:

assert(null);

It does nothing and I am in the debug mode.

Upvotes: 13

Views: 6807

Answers (3)

Stefano Fenu
Stefano Fenu

Reputation: 179

Currently eclipse suggests the following:

Assertions are unreliable. Use BuildConfig.DEBUG conditional checks instead.

Issue Explanation:

Assertions are not checked at runtime. There are ways to request that they be used by Dalvik (adb shell setprop debug.assert 1), but the property is ignored in many places and can not be relied upon. Instead, perform conditional checking inside if (BuildConfig.DEBUG) { } blocks. That constant is a static final boolean which is true in debug builds and false in release builds, and the Java compiler completely removes all code inside the if-body from the app.

For example, you can replace

assert speed > 0 

with

if (BuildConfig.DEBUG && !(speed > 0)) { throw new AssertionError(); }

(Note: This lint check does not flag assertions purely asserting nullness or non-nullness; these are typically more intended for tools usage than runtime checks.)

More Information: [Issue 65183: Intellij/Studio doesn't activate asserts when running Android code in debug mode]OK

Upvotes: 0

hungson175
hungson175

Reputation: 4483

you can just use Android JUnit Assert:

Assert.assertTrue(false);

Upvotes: -3

a.ch.
a.ch.

Reputation: 8380

Yes, they are available.

They are disabled in emulator by default. You will need to add -shell -prop debug.assert=1 command line parameters to Additional Emulator Command Line Options at the run configuration you're using to run your app.

Assertions in eclipse

The other thing you should be aware of is that your application installed on a device will not take into account assertions - they will be ignored.

Upvotes: 16

Related Questions