java.lang.IllegalStateException: context.getSharedPrefere...



这是我的用户类

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( 不得为空"此错误消息。

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

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

相关内容

  • 没有找到相关文章

最新更新