|
|
Why this FAQ doesn't have answers to my questions?
FAQ is still very draft. Do you have any suggestions? Write to our mailing list.
What is Mockito?
Test Spy framework that allows to verify behaviour (like mocks) and stub methods (like good old hand-crafted stubs). See the main page for more.
Why Mockito is so simple? I need xxx feature!
To promote simple test code that hopefully pushes the developer to write simple and clean application code. Need a feature? Please send us an example where you need something more than Mockito can offer.
Can I mock static methods?
No. Mockito prefers object orientation and dependency injection over static code. If you deal with scary legacy code you can use JMockit to mock static methods.
Why can't I "reset" a mock?
The lack of a reset method is deliberate to promote good testing habits and to make the API simpler. Please consider writing simple, small and focused test methods over lengthy, over-specified tests. The discussion about this feature is here. If you have an example from your code where reset() would be useful - please write to our mailing list.
How can I stub a method to return something twice
Stubbing is stateless to simplify the API and promote simple test code. Stubbing a method to return a value means that this value will be returned all the time. However, you can stub the same method to return different values for different arguments. See this thread for discussion about stubbing iterators. If you have an example from your code where this would be useful - please write to our mailing list.
Can I verify toString()?
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.
Once I've stubbed a method to throw an exception, can I override it?
Due to the nature of Mockito syntax you can't. Once a the same method with the same args has been stubbed to throw an exception it cannot be overridden. However, return-value stubs can always be overridden.
//you *can* do this:
stub(mock.get(10)).toThrow(new Exception());
stub(mock.get(20)).toThrow(new Exception());
//or this:
stub(mock.get(10)).toReturn("10");
stub(mock.get(10)).toReturn("10");
//but you *cannot* do this:
stub(mock.get(10)).toThrow(new Exception());
stub(mock.get(10)).toThrow(new Exception());
Please consider writing small, focused test methods with explicit stubbing (e.g: stub to throw in one test and stub to return in other test). Throwing an exception and returning a value are clearly different variants of behaviour and they deserve separate test methods.
If you have an example of a unit test that requires this ability, please send us details.
Sign in to add a comment
