mock case class in scala : Mockito

天涯浪子 提交于 2020-08-26 03:40:22

问题


In my play application i intend to mock a case class. I am able to do so but it creates an object with all member variables null. Is there a way to create mock objects of a case classes such that the object can have some members initialized?

case class User(name: String, address: String)    
val mockUser = mock[User]
user.name // null
user.address //null

how do i create a mockUser such that i can assign some values to name and address?

Edit:

I need the ability to mock the object because i want to have predefined behavior of one of the member method. (This member method calls an external service and i dont want the external service call while doing a unit test.) The member method is called inside another member method, which i want to test.


回答1:


You should never need to mock case classes. It's like "mocking an integer".

What's wrong with val mockUser = User("mockName", "mockAddress")?




回答2:


It should be as simple as this:

when(mockUser.name).thenReturn("Bob")

As far as:

You should never need to mock case classes. It's like "mocking an integer".

False. (IMHO)

What's wrong with val mockUser = User("mockName", "mockAddress")?

Nothing if you dont think there's anything wrong with

val mockFoo = FooWith20Properties("1", "2", "3",..."20")

Your tests will work but you've missed the point of using a mocking framework to reduce your test boilerplate.

Having said that there does seem to be a divide between those that think case classes should be final and those that dont. If you mark yours final then mocking wont work without resorting to something equally controversial such as Powermock.




回答3:


I would move your external service call out of the case class, into a service class and then mock this service class.

Usually, case classes represent data. It leads to neater code if data and the functions which use that data (e.g. your external call) are separate.

I would write code like

case class User(name: String, address: String)

class UserService {
  def callExternalService(user: User): Result = ???
}

val testUser = User("somebody", "somewhere")
val mockService = mock[UserService]
when(mockService.callExternalService(testUser)).thenReturn(...)


来源:https://stackoverflow.com/questions/37184528/mock-case-class-in-scala-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!