问题
I'm trying to implement an easy junit test for a method. My intention is to test if the method parameter is not null
. So that the test fails if the parameter is null
.
the method is:
/*
* @return the db entry object
*/
getEntry( String user, String grp, int status);
My first try to implement the test is
public void testGetEntry() {
String userId = null;
getEntry( userId, "grp1", 3);
asserNotNull(userId);
}
I think thats not the correct way. thx for any help :)
回答1:
You can't test that. You can test a beavhior like : "Check that a IllegalArgumentException is thrown if a null parameter is passed". A unit test for testing if a parameter is not null does not make sense, it is not the purpose of unit testing : https://en.wikipedia.org/wiki/Unit_testing
Here, "test if the method parameter is not null" should be done in the method.
回答2:
You should definitely check out NullPointerTester from Guava. You use it in your tests like this:
new NullPointerTester().testAllPublicInstanceMethods(YourClass.class)
Then you need to annotate your methods with JSR-305s @NonNull
getEntry(@NonNull String user, @NonNull String grp, int status);
Then use Preconditions checkNotNull in your production code.
getEntry(@NonNull String user, @NonNull String grp, int status)
{
Preconditions.checkNotNull(user, "user must be specified");
Preconditions.checkNotNull(grp, "grp must be specified");
//return entry;
}
This will make other classes receive a NullPointerException when they misuse your class. When they receive this they'll know that they did something wrong.
回答3:
In order to check that your method doesn't have a null parameter, you need to use Mockito and mock the class( let's call it C.java) where this method ( let's call it m(param) ) is declared. Of course class C should NOT be the class you want to test (a mock is a "dummy" implementation).
If you are in the case where you are calling the method m of class C and you want to verify that the argument "param" of m(param) is not null, here is how to do it :
C cMock= Mockito.mock(C.class);
verify(cMock).m(isNotNull());
Here is some useful documentation :
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html
http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html
I hope this helps
Regards
来源:https://stackoverflow.com/questions/16607975/junit-not-null-test