mockito
Mocking framework for unit tests written in Java
I read a few threads here about static methods, and I think I understand the problems misuse/excessive use of static methods can cause. But I didn't really get to the bottom of why it is hard to mock static methods.
I know other mocking frameworks, like PowerMock, can do that but why can't Mockito?
I read this article, but the author seems to be religiously against the word static
, maybe it's my poor understanding.
An easy explanation/link would be great.
Source: (StackOverflow)
Consider a method signature like:
public String myFunction(String abc);
Can Mockito help return the same string that the method received?
Source: (StackOverflow)
I've written a factory to produce java.sql.Connection
objects:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
I'd like to validate the parameters passed to DriverManager.getConnection
, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?
Source: (StackOverflow)
How to mock methods with void return type?
I implemented an Observer pattern but I can't mock it with Mockito because I don't know how.
And I tried to find an example on the Internet, but didn't succeed.
My class looks like
public class World {
List<Listener> listeners;
void addListener(Listener item) {
listeners.add(item);
}
void doAction(Action goal,Object obj) {
setState("i received");
goal.doAction(obj);
setState("i finished");
}
private string state;
//setter getter state
}
public class WorldTest implements Listener {
@Test public void word{
World w= mock(World.class);
w.addListener(this);
...
...
}
}
interface Listener {
void doAction();
}
The system are not triggered with mock. =(
I want to show above mentioned system state. And make assertion according to them.
Source: (StackOverflow)
With Mockito, I want to verify()
a method call with byte[]
in its argument list, but I didn't find how to write this.
myMethod( byte[] )
I just want something like anyByteArray()
, how to do that with Mockito ?
Source: (StackOverflow)
I want to verify if a method is called twice or more than once through mockito verify. I used verify and it complains like this:
org.mockito.exceptions.verification.TooManyActualInvocations:
Wanted 1 time:
But was 2 times. Undesired invocation:
Source: (StackOverflow)
I've been trying to get to mock a method with vararg parameters using Mockito:
interface A {
B b(int x, int y, C... c);
}
A a = mock(A.class);
B b = mock(B.class);
when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);
assertEquals(b, a.b(1, 2));
This doesn't work, however if I do this instead:
when(a.b(anyInt(), anyInt())).thenReturn(b);
assertEquals(b, a.b(1, 2));
This works, despite that I have completely omitted the varargs argument when stubbing the method.
Any clues?
Source: (StackOverflow)
I have a method that gets called twice, and I want to capture the argument of the second method call.
Here's what I've tried:
ArgumentCaptor<Foo> firstFooCaptor = ArgumentCaptor.forClass(Foo.class);
ArgumentCaptor<Foo> secondFooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar).doSomething(firstFooCaptor.capture());
verify(mockBar).doSomething(secondFooCaptor.capture());
// then do some assertions on secondFooCaptor.getValue()
But I get a TooManyActualInvocations
Exception, as Mockito thinks that doSomething
should only be called once.
How can I verify the argument of the second call of doSomething
?
Source: (StackOverflow)
I have a method call which I want to mock with mockito. To start with I have created and injected an instance of an object on which the method will be called. My aim is to verify one of the object in method call.
Is there a way that mockito allows you to assert or verify the object and it's attributes when the mock method is called?
example
Mockito.verify(mockedObject)
.someMethodOnMockedObject(
Mockito.<SomeObjectAsArgument>anyObject())
Instead of doing anyObject()
i want to check that argument object contains some particular fields
Mockito.verify(mockedObject)
.someMethodOnMockedObject(
Mockito.<SomeObjectAsArgument>**compareWithThisObject()**)
Source: (StackOverflow)
I'm trying to test some legacy code, using Mockito.
I want to stub a FooDao
that is used in production as follows:
foo = fooDao.getBar(new Bazoo());
I can write:
when(fooDao.getBar(new Bazoo())).thenReturn(myFoo);
But the obvious problem is that getBar()
is never called with the same Bazoo
object that I stubbed the method for. (Curse that new
operator!)
I would love it if I could stub the method in a way that it returns myFoo
regardless of the argument. Failing that, I'll listen to other workaround suggestions, but I'd really like to avoid changing the production code until there is reasonable test coverage.
Source: (StackOverflow)
So, I'm creating a mock object as a static variable on the class level like so... In one test, I want Foo.someMethod()
to return a certain value, while in another test, I want it to return a different value. The problem I'm having is that it seems I need to rebuild the mocks to get this to work correctly. I'd like to avoid rebuilding the mocks, and just use the same objects in each test.
class TestClass {
private static Foo mockFoo;
@BeforeClass
public static void setUp() {
mockFoo = mock(Foo.class);
}
@Test
public void test1() {
when(mockFoo.someMethod()).thenReturn(0);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), receiving 0 as the value
}
@Test
public void test2() {
when(mockFoo.someMethod()).thenReturn(1);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), STILL receiving 0 as the value, instead of expected 1.
}
}
In the second test, I'm still receiving 0 as the value when testObj.bar() is called... What is the best way to resolve this? Note that I know I could use a different mock of Foo
in each test, however, I have to chain multiple requests off of mockFoo
, meaning I'd have to do the chaining in each test.
Source: (StackOverflow)
I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have
final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(resulstIWant);
The problem is, in the second line, myClassSpy.method1()
is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever myClassSpy.method1()
is called, the real method won't be called and the resultsIWant
object will be returned.
MyClass
is an interface and myInstance
is an implementation of that, if that matters.
What do I need to do to correct this spying behaviour?
Source: (StackOverflow)
Is there a way to have a stubbed method return different objects on subsequent invocations? I'd like to do this to test nondeterminate responses from an ExecutorCompletionService
. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.
The code I'm looking to test looks something like this.
// Create an completion service so we can group these tasks together
ExecutorCompletionService<T> completionService =
new ExecutorCompletionService<T>(service);
// Add all these tasks to the completion service
for (Callable<T> t : ts)
completionService.submit(request);
// As an when each call finished, add it to the response set.
for (int i = 0; i < calls.size(); i ++) {
try {
T t = completionService.take().get();
// do some stuff that I want to test
} catch (...) { }
}
Source: (StackOverflow)
Is there any way, using Mockito, to mock some methods in a class, but not others?
For example, in this (admittedly contrived) Stock class I want to mock the getPrice() and getQuantity() return values (as shown in the test snippet below) but I want the getValue() to perform the multiplication as coded in the Stock class
public class Stock {
private final double price;
private final int quantity;
Stock(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public double getValue() {
return getPrice() * getQuantity();
}
@Test
public void getValueTest() {
Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);
when(stock.getQuantity()).thenReturn(200);
double value = stock.getValue();
// Unfortunately the following assert fails, because the mock Stock getValue() method does not perform the Stock.getValue() calculation code.
assertEquals("Stock value not correct", 100.00*200, value, .00001);
}
Source: (StackOverflow)