android - 如何测试 api 请求并用假数据填充类?
问题描述
我在 Internet 上找不到解决此问题的方法。还是我的代码很糟糕?
界面
interface GetWeatherService {
@GET("/data/2.5/forecast?")
fun getAllWeather(@Query("q")cityName: String, @Query("APPID")app_id: String, @Query("units")units: String="imperial"): Call<ListWeather>
@GET("/data/2.5/weather?")
fun getCurrentWeather(@Query("q")cityName: String, @Query("APPID")app_id: String, @Query("units")units: String="imperial"): Call<MainWeather>
@GET("/data/2.5/weather?")
fun getWeatherDataFromLocation(@Query("lat")lat: String, @Query("lon")lon: String, @Query("APPID") app_id: String): Call<DataFromLocation>
}
客户
object RetrofitClientInstance {
private var retrofit: Retrofit? = null
private var BASE_URL = "https://api.openweathermap.org/"
val retrofitInstance: Retrofit?
get(){
if(retrofit == null){
retrofit = retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
主要活动()
class MainActivity: AppCompatActivity {
fun getDataFromApi(cityName: String) {
val service = RetrofitClientInstance.retrofitInstance!!.create(GetWeatherService::class.java)
// Service 1
service.getCurrentWeather(cityName, APP_ID).enqueue(object: Callback<MainWeather>{
override fun onFailure(call: Call<MainWeather>, t: Throwable) {
}
override fun onResponse(call: Call<MainWeather>, response: Response<MainWeather>) {
val weather = response.body()
val currentWeather = CurrentWeather(
weather!!.main.temp,
weather.weather[0].description,
weather.name,
weather.weather[0].main
)
updateCurrentWeatherUI(currentWeather)
}
})
service.getAllWeather(cityName, APP_ID).enqueue(object: Callback<ListWeather>{
override fun onFailure(call: Call<ListWeather>, t: Throwable) {
}
override fun onResponse(call: Call<ListWeather>, response: Response<ListWeather>) {
val weather = response.body()!!.list
for(item in weather){
val weatherList = NextFiveDayWeather(
item.dt,
item.main.temp,
item.weather[0].description
)
weatherArray.add(weatherList)
updateUI(weatherArray)
}
}
})
}
}
数据类
data class MainWeather (
var dt: Long,
var main: MainDTO,
var weather: List<WeatherDTO>,
var dt_txt: String,
var name: String
)
data class WeatherDTO (var main: String, var description: String, var icon: String)
data class ListWeather (@SerializedName("list") var list: List<MainWeather>)
我无法测试对 api 的请求,也无法用假数据填充类?请告诉我,我该怎么办?我应该学习什么?而如果你不难,可以为未来出谋划策吗?
解决方案
您可以下载软件 Postman 来测试 api 端点:https ://www.getpostman.com/
推荐阅读
- c# - 子窗体出现在父窗体的控件下方
- sql - Oracle sum 按不同起点的列范围分组
- python - 从特定日期添加未来的随机日期并将结果保存在新列中
- python - 用于计算 txt 文件中单词的 Python 3 函数对一个单词给出了错误的答案……为什么?
- python - 显示发送数据包 PING 数据的日志 无 接收数据包 PONG 数据 在烧瓶 socketio 中无连续
- c# - 深度克隆带有嵌入文档 ID(树结构)的 MongoDb 文档
- php - 拉拉维尔。在测试期间用 DI 容器中的存根替换对象不起作用
- c - 在 STM32F4 上读取输入 GPIO 位
- angular - 为什么 component.ts 不能分配给接口的变量?
- go - Go中的十六进制编码