Reputation: 43
I wish to create a Mockito mock object of the class cls:
public class cls{
private var;
cls(String x){
var = x;
}
}
Here is my code:
cls obj = mock(cls.class)
obj creates sucessfully but var is null because no parameters were passed to the constructor.Furthermore I can not use powermockito. How can I pass parameters to cls's constructor when creating a mock object?
Upvotes: 3
Views: 2439
Reputation: 95764
var
is private. It's an implementation detail. The whole point of Mockito is that you want to avoid any aspects of the existing implementation, and replace it with an object that interacts realistically with your class-under-test despite having an entirely fake implementation.
Under the hood, Mockito uses Objenesis or ByteBuddy to create the object without calling a constructor. So creating a mock is not going to have a realistic constructor in any case. I would recommend instead stubbing any method that consumes var
.
On the other hand, if you want to selectively stub or verify some of those methods but have realistic fields, you could always create a spy:
cls obj = spy(new cls(100));
Because you're calling a real constructor, the class's fields will be set realistically, and then copied into the new object that you're calling obj
.
Upvotes: 3
Reputation: 309008
You don't need to set the variable.
What you need is for clients of your mock to get back expected values when they initiate actions that you control. Pay attention to the methods that are called and the return values.
I'd recommend that you learn and follow Java coding conventions. Your code is harder to read when you don't.
Upvotes: 0