NullPointerException在运行单元测试时获取应用程序上下文

时间:2015-05-18 12:05:22

标签: java android unit-testing android-testing android-context

我有一个自定义的Application类MyApplication(扩展Application)。我有一个getInstance()方法,它只返回自己,这样我就可以从任何地方访问应用程序Context。

我正在尝试对调用MyApplication.getInstance()的方法进行单元测试,但它返回null,因此我的单元测试失败了。

有人知道怎么做吗?或者我是否需要将我的应用程序Context传递给要测试的方法,以便对该方法运行测试。

以下是一些代码:

MyApplication的:

public static String getErrorMessage(int httpStatus)
{
    // GETTING NULL POINTER EXCEPTION ON THIS LINE
    Resources resources = Bakery.getInstance().getApplicationContext().getResources();
    // ...
}

测试方法:

public class ManagerApiTest extends AndroidTestCase
{

    public void testGetErrorMessage() throws Exception
    {
        Resources resources = getContext().getResources();

        String messageInternal = ManagerAPI.getErrorMessage(500);
        assertEquals(resources.getString(R.string.server_error_internal), messageInternal);
    }
}

单元测试类:

public function vote(TokenInterface $token, $object, array $attributes)
{

    $result = VoterInterface::ACCESS_ABSTAIN;

    $academy = $object;
    // object is not an academy, so get it from the context manager
    if (!$academy instanceof Academy) {
        $academy = $this->context_manager->getAcademy();

        // no academy means this voter is useless
        if (!$academy instanceof Academy)
            return $result;
    }

    // get the current user
    $user = $token->getUser();

    // no user, not a valid user, or user has no academy role, voter abstains
    if (!$user || !($user instanceof UserInterface) || !$user->hasRole('ROLE_ACADEMY'))
        return $result;

    // this is the function which increases page load
    $permissions = $this->manager->findPermissionsByUserAndAcademy($academy, $user); 
    ...

1 个答案:

答案 0 :(得分:-1)

尝试更改

public static Bakery getInstance()
{
    return sInstance;
}

public static Bakery getInstance()
{
    if(sInstance != null) {
      return sInstance;
    } else {
       return new Bakery();
    }
}