JUnit不是null测试 [英] JUnit not null test

查看:208
本文介绍了JUnit不是null测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为方法实现简单的junit测试.我的目的是测试方法参数是否不是null.因此,如果参数为null,则测试将失败.

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.

方法是:

/*
 * @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 :)

推荐答案

您绝对应该查看番石榴.您可以像这样在测试中使用它:

You should definitely check out NullPointerTester from Guava. You use it in your tests like this:

new NullPointerTester().testAllPublicInstanceMethods(YourClass.class)

然后,您需要使用 JSR-305 s @ NonNull

Then you need to annotate your methods with JSR-305s @NonNull

getEntry(@NonNull String user, @NonNull String grp, int status);

然后使用前提条件生产代码中的checkNotNull.

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;
}

这将使其他类在滥用您的类时收到NullPointerException.当他们收到此消息后,他们会知道他们做错了什么.

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.

这篇关于JUnit不是null测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆