Reputation: 19
interface CheakeId {
public void verify();
}
class CreateAccount implements CheakeId {
public String gmail(){
return "[email protected]";
}
@Override
public void verify() {
System.out.println("verify");
}
}
CheakId cheakid = Mockito.mock(CreateAccount.class);
Question: Can we store the reference of child class in a reference variable of parent class If we create the mock objects of child class?
class Night {
public void sleep() {
System.out.println("sleep");
}
}
Night night = Mockito.mock(Night.class);
Question: Can we create only mock objects of interfaces or we also can create mock objects of classes without interfaces?
Upvotes: 1
Views: 900
Reputation: 17854
In a distant past, people used Java's dynamic proxy feature to generate mocks, and that only worked for interfaces. See https://www.baeldung.com/java-dynamic-proxies
An alternative way to generate mocks is to use bytecode generators like cglib and bytebuddy, and that also works for classes without interfaces. This is supported since Mockito 1.0, IIRC.
Some limitations apply. E.g. you cannot stub a method that's declared as final in the class, or stub the equals and hashCode methods.
With classes, you can also use 'spy' instead of 'mock' if you want to keep the class's implementation, and use mockito just for verification.
So basically: your code should work.
CheakId cheakid = Mockito.mock(CreateAccount.class);
Night night = Mockito.mock(Night.class);
Upvotes: 2