- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个我想测试的登录演示者。我是单元测试的新手,我已经编写了一个基本测试来测试一个小功能。
class LoginPresenter @Inject constructor(
private val view: LoginView,
private val strategy: CancelStrategy,
private val navigator: AuthenticationNavigator,
private val tokenRepository: TokenRepository,
private val localRepository: LocalRepository,
private val settingsInteractor: GetSettingsInteractor,
private val analyticsManager: AnalyticsManager,
private val saveCurrentServer: SaveCurrentServerInteractor,
private val saveAccountInteractor: SaveAccountInteractor,
private val factory: RocketChatClientFactory,
val serverInteractor: GetConnectingServerInteractor
) {
// TODO - we should validate the current server when opening the app, and have a nonnull get()
private var currentServer = serverInteractor.get()!!
private val token = tokenRepository.get(currentServer)
private lateinit var client: RocketChatClient
private lateinit var settings: PublicSettings
fun setupView() {
setupConnectionInfo(currentServer)
setupForgotPasswordView()
}
private fun setupConnectionInfo(serverUrl: String) {
currentServer = serverUrl
client = factory.get(currentServer)
settings = settingsInteractor.get(currentServer)
}
private fun setupForgotPasswordView() {
if (settings.isPasswordResetEnabled()) {
view.showForgotPasswordView()
}
}
fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
launchUI(strategy) {
view.showLoading()
try {
val token = retryIO("login") {
when {
settings.isLdapAuthenticationEnabled() ->
client.loginWithLdap(usernameOrEmail, password)
usernameOrEmail.isEmail() ->
client.loginWithEmail(usernameOrEmail, password)
else ->
client.login(usernameOrEmail, password)
}
}
val myself = retryIO("me()") { client.me() }
myself.username?.let { username ->
val user = User(
id = myself.id,
roles = myself.roles,
status = myself.status,
name = myself.name,
emails = myself.emails?.map { Email(it.address ?: "", it.verified) },
username = username,
utcOffset = myself.utcOffset
)
localRepository.saveCurrentUser(currentServer, user)
saveCurrentServer.save(currentServer)
localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
saveAccount(username)
saveToken(token)
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
true
)
view.saveSmartLockCredentials(usernameOrEmail, password)
navigator.toChatList()
}
} catch (exception: RocketChatException) {
when (exception) {
is RocketChatTwoFactorException -> {
navigator.toTwoFA(usernameOrEmail, password)
}
else -> {
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
false
)
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
} finally {
view.hideLoading()
}
}
}
fun forgotPassword() = navigator.toForgotPassword()
private fun saveAccount(username: String) {
val icon = settings.favicon()?.let {
currentServer.serverLogoUrl(it)
}
val logo = settings.wideTile()?.let {
currentServer.serverLogoUrl(it)
}
val thumb = currentServer.avatarUrl(username, token?.userId, token?.authToken)
val account = Account(
settings.siteName() ?: currentServer,
currentServer,
icon,
logo,
username,
thumb
)
saveAccountInteractor.save(account)
}
private fun saveToken(token: Token) = tokenRepository.save(currentServer, token)
}
登录Presenter测试
class LoginPresenterTest {
lateinit var loginPresenter: LoginPresenter
private val view = mock(LoginView::class.java)
private val strategy = mock(CancelStrategy::class.java)
private val navigator = mock(AuthenticationNavigator::class.java)
private val tokenRepository = mock(TokenRepository::class.java)
private val localRepository = mock(LocalRepository::class.java)
private val settingsInteractor = mock(GetSettingsInteractor::class.java)
private val analyticsManager = mock(AnalyticsManager::class.java)
private val saveCurrentServer = mock(SaveCurrentServerInteractor::class.java)
private val saveAccountInteractor = mock(SaveAccountInteractor::class.java)
private val factory = mock(RocketChatClientFactory::class.java)
private val serverInteractor = mock(GetConnectingServerInteractor::class.java)
private val token = mock(Token::class.java)
private lateinit var settings: PublicSettings
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
loginPresenter = LoginPresenter(
view, strategy, navigator, tokenRepository, localRepository, settingsInteractor,
analyticsManager, saveCurrentServer, saveAccountInteractor, factory, serverInteractor
)
}
@Test
fun testAttach() {
loginPresenter.setupView()
assertNotNull(view)
}
}
但是在运行测试时,我收到 KotlinNullPointerException,因为变量当前服务器变为空,因为其中没有保存 url。有什么办法可以避免它在运行测试期间为空。我尝试过使用 elvis 运算符并修改 LoginPresenter,但我想知道是否还有其他可行的方法。我只想使用任何 url 字符串初始化当前服务器的值,以避免在运行测试期间出现 NPE。
private var currentServer = serverInteractor.get()?: "https://example.com"
我还有 SaveConnectingServerInteractor 和 GetConnectingServerInteractor 用于在身份验证时存储服务器 url。
class SaveConnectingServerInteractor @Inject constructor(
@ForAuthentication private val repository: CurrentServerRepository
) {
fun save(url: String) = repository.save(url)
}
class GetConnectingServerInteractor @Inject constructor(
@ForAuthentication private val repository: CurrentServerRepository
) {
fun get(): String? = repository.get()
fun clear() {
repository.clear()
}
}
最佳答案
你试过这个吗?
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
whenever(serverInteractor.get()).thenReturn("http://fakeurl")
loginPresenter = LoginPresenter(
view, strategy, navigator, tokenRepository, localRepository, settingsInteractor,
analyticsManager, saveCurrentServer, saveAccountInteractor, factory, serverInteractor
)
}
whenever
方法来自 https://github.com/nhaarman/mockito-kotlin .
编辑:或者,如果您不想依赖mockito-kotlin,也可以使用 when
关键字-
`when`(serverInteractor.get()).thenReturn("http://fakeurl")
关于java - 如何模拟包含可能引发 NPE 的变量的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467566/
目前,我的经验是,一段利用Google Drive API的代码在没有引入ProGuard的情况下运行得很好。。然而,在引入ProGuard之后,我得到了以下运行时错误。。请注意,崩溃发生在我的代码(
今天早上我遇到了一个非常奇怪的 NPE,并将其简化为一个简单的示例。这是 JVM 错误还是正确的行为? public class Test1 { class Item { In
在 crashlytics 中报告的 NPE 仅适用于 Android O 及更高版本。我只是在 onCreate 方法中 startForegroundService 和服务 startForgro
运行以下内容: public class NPESample { String value; public static void main(String[] args) { NPES
我有一个非常简单的 OpenAPI/Swagger 配置 (openapi.yaml): swagger: '2.0' info: title: My Service version: 1.0
我正在使用 com.sun.media.imageioimpl.plugins.tiff.TIFFPackBitsCompressor 尝试对使用 PackBits 的 tiff 字节数组进行编码。我
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) findViewById returns null
我有一个处理大量数据的批处理作业。该作业基本上从源数据库获取数据并进行 Web 服务调用,然后将数据写入目标数据库。今天我遇到了“NPE”,我在其中检查 XML 是否有“成功”响应。我检查其中一个节点
这个问题已经有答案了: Why does a ternary conditional expression returning null and assigned to a reference typ
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) 已关闭 4 年前。 我正在尝试从 bundle 内的
我试图在我的应用程序中每隔一分钟执行一项任务,我使用以下内容来实现相同的目的。代码位于onCreate方法内部: mTimer.scheduleAtFixedRate(new TimerT
所以我正在使用集合设计模式并使用数组列表。每当我尝试向数组列表中添加某些内容时,我都会收到 NPE。我可能错误地实现了该集合,因此出现了 NPE。 我不想复制我的整个代码,因为它太长了,所以我试图给你
我想将自定义对话框的一个区域设置为所选图像。如果我设置整个应用程序的背景图像,下面的代码可以进行一些重新安排。由于某种原因,当我移动它来设置自定义对话框的区域时,我收到以下错误: 错误: 11-03
所以我觉得自己像个白痴,但我正在尝试实现碰撞检测,并且我需要检查玩家旁边是否有方 block 。当我去检查时,我首先会看看我要找的瓷砖是否真的在那里。如果是,我将继续选择该图 block 并从中创建一
在 OS X 10.11 上,我们的应用程序用户会遇到一些没有堆栈跟踪的 NPE(请参阅 this stackoverflow-question)。我现在想自己创建一个来调试这种情况下的错误处理。 如
我有一个非常简单的 OpenAPI/Swagger 配置 (openapi.yaml): swagger: '2.0' info: title: My Service version: 1.0
我正在尝试为名为 getBestSellers() 的方法编写单元测试。 这里是: package bookstore.scraper.book.scrapingtypeservice; import
为什么我在以下作业中获得 NPE: mPyramid[row][column] = temp; 这是我的代码: Block temp; Block[][] pyramid =
为什么这段代码会导致NPE? Findbugs 给了我提示,这种情况可能会发生,而且有时确实会发生:-) 有什么想法吗? public Integer whyAnNPE() { return
我正在尝试运行客户端并访问字段来设置/获取值。当脚本启动时,我创建一个加载了 URLClassLoader 的客户端类的新实例,并将其分配给 gameApplet。 现在,下一段代码可以正常工作(访问
我是一名优秀的程序员,十分优秀!