Mockito Interview Questions
Mockito Interview Questions
Mockito Interview Questions
#Today's uploaded
#Mockito #Interview #Questions #Answers
Question 1. What Is Mockito?
Answer :Mockito allows creation of mock object for the purpose of Test Driven
Development and Behavior Driven development. Unlike creating actual object, Mockito
allows creation of fake object (external dependencies) which allows it to give
consistent results to a given invocation.
Question 2. Why Do We Need Mockito? What Are The Advantages?
Answer :Mockito differentiates itself from the other testing framework by removing
the expectation beforehand. So, by doing this, it reduces the coupling. Most of the
testing framework works on the "expect-run-verify". Mockito allows it to make it
"run-verify" framework. Mockito also provides annotation which allows to reduce the
boilerplate code.
Answer :
In Mockito, you always check a particular class. The dependency in that class is
injected using mock object. So, for example, if you have service class, then the
Dao class are injected as a mockDao. This enables us to check only the method of
that given service class and whether they are performing as expected or not.
For example, suppose, service class has an updateObject Method. That update method
is depend on Dao1, Dao2. Here the objective is to test only the updateObject method
and not the Dao1 and Dao2. So, we can create a mockDao and return a mock object.
This object is not the one which is in the database but is custom made. It only
tests whether the updates are happening as expected or not. The syntax to create a
Mock object is as follows:
Answer :
Answer :
We need to create the mock object and need to pass the invocation. We must override
the method in the actual DB with the method over here and pass the response object.
Mockito.when(mockObjectDao.find((Guid) Mockito.anyObject())).thenAnswer(new
Answer<responseObject>() {
@Override
public responseObject answer(InvocationOnMock invocation) throws Throwable {
Guid responseObjectID = (Guid) invocation.getArguments()[0];
responseObject responseDbObject = new responseObject();
responseDbObject.setresponseObjectId(responseObjectID);
responseObjectLink responseObjectLink = new responseObjectLink();
responseObjectLink.setLedgerBookId(Guid.createGuid());
responseObjectLink.setresponseObjectId(responseObjectID);
responseObjectLink.setLedgerObjectId(Guid.createGuid());
responseDbObject.getresponseObjectLinks().add(responseObjectLink);
for (Contact sourceContact : responseObjectDTO.getSourceContacts()) {
if (!sourceContact.getObjectId().equals(responseObjectID)) {
responseObjectLink = new responseObjectLink();
responseObjectLink.setLedgerBookId(sourceContact.getAddressBookId());
responseObjectLink.setresponseObjectId(responseObjectID);
responseObjectLink.setLedgerObjectId(sourceContact.getObjectId());
responseDbObject.getresponseObjectLinks().add(responseObjectLink);
}
}
return responseDbObject;
}
});
Question 6. Which Of The Following Are Usually Automated And Which Are Executed
Manually ?
1. Unit Test
2. Integration Test
Answer :
Unit Test are usually automated and Integration Tests are usually executed
manually.
Answer :
Answer :
Question 9. How To Test Whether The Returns Value Of The Method Is Expected ?
Answer :
Using Assert.
Answer :
Junit fails.
Question 11. How To Create A Junit To Make Sure That The Tested Method Throws An
Exception ?
Answer :
Question 12. What Should I Do If I Want To Make Sure That A Particular Method Of A
Class Is Getting Called?
Answer :
If its a static method of the class , we can use verify to make sure it's getting
called.
If its an instance method , We can mock the object and then use verify with the
mocked object to make sure that the method is getting called."
Answer :
Answer :
In case we need to verify that a method is being called with any argument and not a
specific argument we can use Mockito.any(Class), Mockito.anyString, Mockito.anyLong
etc.
Answer :
We can remove @Test from the respective test so as to avoid its execution.
Alternatively we can put @Ignore annotation on the Junit file if we want to ignore
all tests in a particular file.
Question 16. How Can We Test Methods Individually Which Are Not Visible Or Declared
Private ?
Answer :
We can either increase their visibility and mark them with annotation
@VisibleForTesting or can use reflection to individually test those methods.
Answer :
Answer :
To promote simple test code that hopefully pushes the developer to write simple and
clean application code. I wrote this paragraph long before version 1.5. Mockito is
still quite lean but the number of features increased because many users found
valid cases for them.
Answer :
Requires Java 6+
Cannot mock static methods
Cannot mock constructors
Cannot mock equals(), hashCode(). Firstly, you should not mock those methods.
Secondly, Mockito defines and depends upon a specific implementation of these
methods. Redefining them might break Mockito.
Mocking is only possible on VMs that are supported by Objenesis. Don't worry, most
VMs should work just fine.
Spying on real methods where real implementation references outer Class via
OuterClass.this is impossible. Don't worry, this is extremely rare case.
Mockito 1.x Specific limitations
Needs Java 5+
Cannot mock final classes
Cannot mock final methods - their real behavior is executed without any exception.
Mockito cannot warn you about mocking final methods so be vigilant.
Cannot mock static methods
Cannot mock constructors
Cannot mock equals(), hashCode(). Firstly, you should not mock those methods.
Secondly, Mockito defines and depends upon a specific implementation of these
methods. Redefining them might break Mockito.
Mocking is only possible on VMs that are supported by Objenesis (Note Objenesis is
in version 2.1). Don't worry, most VMs should work just fine.
Spying on real methods where real implementation references outer Class via
OuterClass.this is impossible. Don't worry, this is extremely rare case.
Question 20. Do You Mock Classes & Interfaces?
Answer :
Answer :
Answer :
No. Mockito prefers object orientation and dependency injection over static,
procedural code that is hard to understand & change. If you deal with scary legacy
code you can use JMockit or Powermock to mock static methods.
Answer :
Answer :
For healthy scenarios Mockito plays nicely with threads. For instance, you can run
tests in parallel to speed up the build. Also, you can let multiple threads call
methods on a shared mock to test in concurrent conditions. Check out a timeout()
feature for testing concurrency.
Answer :
No. You can stub it, though. Verification of toString() is not implemented mainly
because:
When debugging, IDE calls toString() on objects to print local variables and their
content, etc. After debugging, the verification of toString() will most likely
fail.
toString() is used for logging or during string concatenation. Those invocations
are usually irrelevant but they will change the outcome of verification.
Question 26. Can I "reset" A Mock?
Answer :
Recently we decided to go on with this feature for tricky scenarios where mocks are
created by the container. Before that, the lack of a reset method was deliberate to
promote good testing habits and to make the API simpler.
Instead of reset() please consider writing simple, small and focused test methods
over lengthy, over-specified tests.
Answer :
Mockito validates if you use it correctly all the time. Examples of incorrect use:
Mockito throws exceptions if you misuse it so that you will know if your tests are
written correctly. The only problem is that Mockito does the validation next time
you use the framework. Therefore sometimes the exception is thrown in the next test
and you have to manually find the previous test that was not written correctly.
Answer :
Answer :
when(m.foo()).thenReturn(mock(Foo.class));
// ^
The reason is that detecting unfinished stubbing wouldn't work if we allow above
construct. We consider this as a 'trade off' of framework validation (see also
previous FAQ entry). However you can slightly change the code to make it working:
Answer :
sort of stubbing, e.g. mock to return mock, to return mock, etc. should be used
very sporadically, ideally never. It clearly points out violation of the Law of
Demeter. You don't want to mess with Demeter. Since you have been warned check out
Mockito deep stubs.
Question 31. Will This Library Help Mocking Closed (non-open) Classes?
Answer :
Mockito-Kotlin does not really add any extra functionality to Mockito. As such, you
will still get exceptions when trying to mock closed classes. If possible, try to
use interfaces instead.
Question 33. I Get An Error �resolved Versions For App (1.1.x) And Test App (1.0.x)
Differ�. What Should I Do?
Answer :
subprojects {
configurations.all {
resolutionStrategy {
forcedModules = [
"org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion",
"org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
]
}
}
}
If you don�t want to force dependencies like this, you can alternatively depend on
the newer version of kotlin-reflect explicitly, which will make Mockito-Kotlin use
that version as well:
testCompile 'com.nhaarman:mockito-kotlin:x.x.x`
testCompile 'org.jetbrains.kotlin:kotlin-reflect:1.1.1'
Answer :
No. Mockito 2.x is officially released and this library will focus on these
versions.
Answer :