android - Android unit testing Location not mocked
问题描述
I am trying to test my presenter and I need a mocked location, however, I get null or have default values such as 0.0 for lat, long, bearing and so on
I have already tried creating a new Location object and initializing all the fields I need.
val latitude = 37.422
val longitude = -122.084
val mockLocation = mock(Location::class.java)
mockLocation.latitude = latitude
mockLocation.longitude = longitude
presenter.loadsAirpots(latitude, longitude)
presenter.locationChanged(mockLocation)
System.out.println(mockLocation.latitude)
I expect latitude to be 37.422 but the actual output is 0.0
解决方案
When you mock an object the real implementation won't be called.
You are trying to call setLatitude(latitude)
but it won't change the value.
If you want to mock the object you should do:
val mockLocation = mock(Location::class.java)
given(mockLocation.getLatitude()).willReturn(latitude)
given(mockLocation.getLongitude()).willReturn(longitude)
Or you could create a real object:
val realLocation = Location("provider")
realLocation.latitude = latitude
realLocation.longitude = longitude
推荐阅读
- python - 如何将带有 selenium python 的文本发送到 a 内的 iframe?
- r - 在 R (2020) 上安装预测包时出错
- c# - 如何在没有未知密钥的情况下访问 Json 数据?C# Unity3D
- python - Python - 切片错误:IndexError:索引 3 超出轴 2 的范围,大小为 3
- ruby - Ruby 的虚拟属性和继承超级
- r - 如何编写一个循环来查找跨列的中位数
- javascript - 我想知道是否使用(fs)我可以将文件夹从一个位置复制到另一个位置
- c# - Windows 窗体:在特定时间段内处理两次按钮单击
- php - htaccess 内联或条件
- python - 如何解开系统和 brew python