对视图模型进行单元测试时,列表始终返回空



我正在尝试学习单元测试,我将我的代码分解到 MVVM(i( 架构中,但是当我运行我的 testParseToList(( 测试函数时,它总是返回一个空列表,我不知道为什么。 我担心这可能与 MVVM(i( 的 i 部分以及我是否正确地嘲笑我的视图模型有关。 我从最简单的视图模型开始,希望在进入更复杂的概念之前掌握这些概念。

OfflineViewModelUnitTest.kt

@RunWith(JUnit4::class)
class OfflineViewModelUnitTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@Mock
var offlineViewModel: OfflineViewModel = OfflineViewModel(OfflineInteractorImpl())
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
DaggerOfflineViewModelComponent.builder()
.offlineInteractorImplModule(OfflineInteractorImplModule())
.build()
.inject(offlineViewModel)
//        this.offlineViewModel = OfflineViewModel(OfflineInteractorImpl())
}
@Test
fun testParseToList() {
val test = offlineViewModel.parseTextToList("dried bonito extract,n" +
"    ketchup,n" +
"    millet,n" +
"    corn & wheat protein")
val a = "dried bonito extract"
val b = "ketchup"
val c = "millet"
val d = "corn & wheat protein"
val expectedResult = listOf(a, b, c, d)
assertEquals(expectedResult, test)
}
}

OfflineViewModel.kt

class OfflineViewModel(private val offlineInteractor: OfflineInteractor): ViewModel() {
init {
DaggerOfflineViewModelComponent.builder()
.offlineInteractorImplModule(OfflineInteractorImplModule())
.build()
.inject(this)
}
fun parseTextToList(firebaseVisionTextString: String): MutableList<String> {
Log.d("here it is", firebaseVisionTextString)
return offlineInteractor.parseTextToList(firebaseVisionTextString)
}
fun readCsvFromAssetFolder(inputStream: InputStream): List<String>{
return offlineInteractor.readCsvFromAssetFolder(inputStream)
}
}

OfflineInteractorImpl.kt

class OfflineInteractorImpl: OfflineInteractor {
override fun parseTextToList(firebaseVisionTextString: String): MutableList<String> {
val ingredientsList: MutableList<String> = firebaseVisionTextString.split(",").map { it.trim() }.toMutableList()
return ingredientsList
}
override fun readCsvFromAssetFolder(inputStream: InputStream): List<String> {
val csvLine: ArrayList<String> = ArrayList()
var content: Array<String>?
try
{
val br = BufferedReader(InputStreamReader(inputStream))
for (line in br.lines())
{
content = line.split((",").toRegex()).dropLastWhile{ it.isEmpty() }.toTypedArray()
csvLine.add(content[0].substringBefore(";"))
}
br.close()
}
catch (e: IOException) {
e.printStackTrace()
}
return csvLine
}
}

测试结果

java.lang.AssertionError: 
Expected :[dried bonito extract, ketchup, millet, corn & wheat protein]
Actual   :[]

就像第二个说的,因为你模拟了离线视图模型,它将返回一个空字符串,除非你定义了一些东西让它使用 when(( 返回。

来源:https://github.com/mockito/mockito/wiki/FAQ#what-values-do-mocks-return-by-default

相关内容

  • 没有找到相关文章

最新更新