I'm using other teams api(let's name it otherTeamAPI) to call data, so in my function, my code looks like this:
def getData(host:String, port:Int, date: String): Map[String, String] = {
val data = new otherTeamAPI(host,port)
val latestData = data.getLatestData(date)
}
Could someone teach me how to use Mockito to do the same thing to get data
in unit test? I'm not sure whether to use something like below to new an api
:
val otherTeamAPI = Mock[otherTeamAPI]
otherTeamAPI.getLatestData(date)
How to get data
everytime i trigger my function getData
? Do i need to do somthing new a mock otherTeamAPI
?
CodePudding user response:
Your code, written as is, is not testable. You have to be able to pass your method an instance of the OtherTeamAPI
so that your production code uses a real instance but test code can use a fake one (a "mock").
How you pass this instance depends on the structure of the rest of your code: either as a parameter of this method getData
or as an attribute of the class that contains it.
The first one would look like this:
def getData(api: OtherTeamApi, date: String): Map[String, String] = {
val latestData = api.getLatestData(date)
// ...
}
And then in your test, you can do something like:
val fakeApi = mock[OtherTeamAPI]
when(fakeApi.getLatestData(anyString())).the return(...)
val result = getData(fakeApi, ...)
// Then assert on result
This is a high level answer. You'll need to learn more about Mockito to find out what you want to do.
CodePudding user response:
Thank you!! As i'm a green hand, I'm not quite understand why i can't test it in my original code? I change my code to add implicit:
def getData(date: String)(implicit api : OtherTeamAPI): Map[String, String] = {
val latestData = api.getLatestData(date) // ...
}
Then in my test, I change it to:
implicit val mockapi : OtherTeamAPI = mock[OtherTeamAPI]
when(mockapi.getLatestData(date)).thenReturn(...)
Then if i want to test the getData
function, would try this:
getData(date)
But I get an error in when(mockapi.getLatestData(date))
- Unspecified value parameters: value : Any.
Could you help on this? Thanks in advance!