danielspaniol
danielspaniol

Reputation: 2328

JUnit4 - Test if method does nothing

How can I test if a method does nothing. For example I have a static method that throws an exception if the given string-argument is null or empty (it's meant for argument-validation). Right now my tests look like this:

@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
    Require.notNullOrEmpty(Generate.randomString());
    assertTrue(true); // <- this looks very ugly
}

@Test(expected = IllegalArgumentException.class)
public void notNullOrEmpty_throwsExceptionIfValueIsNull() {
    Require.notNullOrEmpty(null);
}

@Test(expected = IllegalArgumentException.class)
public void notNullOrEmpty_throwsExceptionIfValueIsEmpty() {
    Require.notNullOrEmpty("");
}

How can I make the first test to pass without calling assertTrue(true), there is a Assert.fail() is there something like an Assert.pass()?

EDIT: Added missing (expected = IllegalArgumentException.class) to 3rd test

Upvotes: 2

Views: 9822

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 30995

You have just to remove the assert in the first method.

@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
    Require.notNullOrEmpty(Generate.randomString());
    // Test has passed
}

If the test method runs completely then it means it pass with success. Look at Eclipse junit output:

enter image description here

Update: as an additional comment, if you use Mockito framework you can leverage verify method to verify that a method was called X times. For instance, I used something like this:

verify(cmAlertDao, times(5)).save(any(CMAlert.class));

In your case, since you are testing static methods, then you might find useful using PowerMock which allows you to verify static methods (since Mockito doesn't). And you can use verifyStatic(...).

Upvotes: 6

davidxxx
davidxxx

Reputation: 131346

A unit test must assert which is expected in the behavior of the method.
If in your specification, when your call notNullOrEmpty()no exception must be thrown when the data is valid and an exception must be thrown when the data is not valid so in your unit test you must do no assertion when the data is valid since if it doesn't success, a exception will be thrown and the test will so be in failure.

@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
    Require.notNullOrEmpty(Generate.randomString());
}

Upvotes: 0

DimaSan
DimaSan

Reputation: 12684

You should add @Test(expected = YourException.class) annotation.

Try to add to the first test:

@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
    String str = Generate.randomString();
    Require.notNullOrEmpty(str);
    assertNotNull(str);
}

and probably to you have better to rename it to notNullOrEmpty_doesNothingIfValueIsNotNullOrNotEmpty because you are testing it for not empty value.

Upvotes: 4

Related Questions