我想通过读取我拥有的json文件进行单元测试,该文件与API返回的方案相同。但是我承认我丝毫不知道如何开始。
场景如下:当应用程序通过ViewModel的观察者加载片段时,将对API进行改造。我在“ test / res /”的.json文件中拥有该调用响应的JSON,在我的第一个测试中,我只想测试“ code”参数的返回值是否等于200
服务界面
@GET("characters")
fun getCharacters(@Query("ts") ts: String,
@Query("apikey") apiKey: String,
@Query("hash") hash: String,
@Query("limit") limit : String = "80"): Call<ReturnData>
型号
data class ReturnData(
val attributionHTML: String,
val attributionText: String,
val code: Int,
val copyright: String,
val `data`: Data,
val etag: String,
val status: String
)
class HomeViewModel(private val repository: MarvelRepository = MarvelRepositoryImpl(),
private val fragment: HomeFragment = HomeFragment.newInstance())
: ViewModel() {
fun getHeroes(){
//fragment.showLoading()
repository.getCharacter(object : OnGetMarvelCallback{
override fun onSuccess(response: ReturnData) {
Log.d("Reponse", "It's Ok!!!")
heroesList.value = response
//fragment.hideLoading()
}
override fun onError() {
Log.e("ErrorViewModel", "Error in viewmodel call")
//fragment.hideLoading()
}
})
}
}
class HomeViewModelTest {
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
@Throws(Exception::class)
fun fileObjectShouldNotBeNull() {
//val file = getFileFromPath(this, "mock_response_error_404.json")
val file = readFileFromJson( "mock_response_error_404")
assertThat(file, notNullValue())
}
fun readFileFromJson(fileName: String): String{
val br = BufferedReader(InputStreamReader(FileInputStream(fileName)))
val sb = StringBuilder()
var line = br.readLine()
while (line != null){
sb.append(line)
line = br.readLine()
}
return sb.toString()
}
private fun getFileFromPath(obj: Any, fileName: String): File {
val classLoader = obj.javaClass.classLoader
val resource = classLoader!!.getResource(fileName)
return File(resource.path)
}
}
除了这些类外,还具有负责执行对MarvelAPI服务的调用的存储库。运行这些测试会给我带来以下异常:java.io.FileNotFoundException:mock_response_error_404(没有此类文件或目录)。