java.lang.IllegalStateException:context.getSharedPrefere ... EF,Context.MODE_PRIVATE)不能为null

时间:2018-06-02 05:39:00

标签: android kotlin mockito

这是我的用户类

open class User(val context: Context) : Serializable {

@SerializedName("token")
var tokenFromServer: String = ""
var tokenSharedPreferences: SharedPreferences =context.getSharedPreferences(Constants.USER_TOKEN_PREF, Context.MODE_PRIVATE)

@SerializedName("registered_token")
var token: String = ""
    set(userNewToken) {
        field = userNewToken
        with(tokenSharedPreferences.edit()) {
            putString(Constants.TOKEN_KEY, userNewToken).commit()
        }
        checkLogin() // 토큰이 설정 되면 로그인 상태 변경해준다
    }

fun checkLogin(): Boolean {
    with(context.getSharedPreferences(Constants.USER_TOKEN_PREF, Context.MODE_PRIVATE).getString(Constants.TOKEN_KEY, Constants.EMPTY_TOKEN)) {
        if (this == Constants.EMPTY_TOKEN) return false else return true
    }
    return false
}
}

这是我的测试代码

 @RunWith(MockitoJUnitRunner::class)
 class UserModelTest : InstrumentationTestCase() {

private val TEST_TOKEN_FROM_SERVER = "token"

@Mock
private lateinit var mockUserModel: User
private lateinit var realUserModel: User
var testContext = mock(Context::class.java)

@Before
fun initMocks() {
    testContext = MockContext()
    mockUserModel = User(testContext)
    realUserModel = User(testContext)


    given(realUserModel.tokenSharedPreferences.getString(eq(Constants.TOKEN_KEY), anyString()))
            .willReturn(realUserModel.token)

}
}

我得到" java.lang.IllegalStateException:context.getSharedPrefere ... EF,Context.MODE_PRIVATE)不能为空"此错误消息。

1 个答案:

答案 0 :(得分:0)

您的代码context.getSharedPreferences(Constants.USER_TOKEN_PREF, Context.MODE_PRIVATE)返回null,因此存储此值的变量必须是可为空的:

var tokenSharedPreferences: SharedPreferences? =context.getSharedPreferences(Constants.USER_TOKEN_PREF, Context.MODE_PRIVATE)