It seems mockito only verifies whether a method of a mock object is called and the mock object always have something like doReturn().when(mock object)
But can I create a mock object and define doReturn().when(mock object)
and then verify a method of another object is called?
Here is what I want to do: I define a mockEnvironment and return a response no matter what happens. But then I want to verify different methods of anotherObj is called in different cases.
How to do that?
public class BaseClass {
private Environment mockEnvironment;
#Test
public void testcase () {
setMockitoEnvironment();
response = foo(mockEnvironment, argument1);
verify(anotherObj).codePath1(...);
response = foo(mockEnvironment, argument2);
verify(anotherObj).codePath2(...);
}
}
//this method successfully return a response with any input
//because I do not care how response is eventually generated,
//I only care whether code path reaches createResponse() via
//code path 1 or code path 2.
private void setMockitoEnvironment() {
mockEnvironment = mock(Environment.class);
doReturn (response).when(mockEnvironment).createResponse(for any input);
}
private Response foo(...) {
...
return createResponse(...);
}
You can use a Mockito Spy for this. If you setup anotherObj as a spy you can verify method calls on that object. In your example you need to make sure that the call to foo uses the spy instead of an ordinary implementation of anotherObj. The spy is setup something like this:
AnotherClass anotherObjSpy = Mockito.spy(new AnotherClass());
// do stuff -- e.g. anotherObjSpy.foo(...);
verify(anotherObjSpy).codePath1(...);
Annotate the non-mock object with #Spy annotation and then check for verify(). Check this
Related
If I have a object MyObject, I want to return some value if certain method of that object is called. For example something like this:
doReturn(someValue).when(Mockito.any(MyObject.class)).getSomeValue();
I have tried it like that, but it does not works :
org.mockito.exceptions.misusing.NullInsteadOfMockException:
Argument passed to when() is null!
You need to use Mockito.mock(MyObject.class) to create a mock of your object.
Currently you're using Mockito#any which is a parameter matcher used to define behavior on a mock when a stubbed method is called for any given parameter.
#Test
public void testMock() throws InterruptedException {
MyObject myObjectMock = Mockito.mock(MyObject.class);
doReturn(2).when(myObjectMock).getSomeValue();
System.out.println(myObjectMock.getSomeValue()); // prints 2
}
private class MyObject {
public int getSomeValue() {
return 1;
}
}
Alternatively, you can use Mockito annotations:
#RunWith(MockitoJUnitRunner.class)
public class YourTestClass {
#Mock
MyObject myObjectMock
saves you from manually mocking that object within your setup or test methods.
Here is the scenario, I have something like this in one of my method of cls:
public class xyz{
public Object build(Map map) {
BaseClass cls;
if(SomeconditionTrue) {
cls = new ChildClass1(new ABC());
} else {
cls = new ChildClass2(new ABC());
}
cls.callMethod();
}
}
For the above scenario, I am writing a test case using PowerMockito, I want to mock this method call, cls.callMethod(). When i am trying the normal mocking, it calls the actual Method callMethod() that is failing. can some body please help me to mock that method call? Tried using couple of scenarios using PowerMockito.stub and some of other options, but its always calling the actual method.
Using Powermock you could do something like the following:
PowerMockito.whenNew(ChildClass1.class)
.withArguments(any(ABC.class))
.thenReturn(mockedBaseClass);
PowerMockito.whenNew(ChildClass2.class)
.withArguments(any(ABC.class))
.thenReturn(mockedBaseClass);
Of course my preferred approach would be to pass in a factory that knows about how to make these ChildClass instances, then you could mock it using Mockito and it would be cleaner. However if that is not an option, hopefully the above should work.
I have to deal with a legacy application that has no tests. So before I begin refactoring I want to make sure everything works as it is.
Now imagine the following situation:
public SomeObject doSomething(final OtherObject x, final String something) {
if(x != null) {
final String = someOtherMethod(x, something);
}
}
protected String someOtherMethod(final OtherObject x, final String something) {
....
}
Now I want to make sure that protected method is called as well
So I did this
#InjectMocks // Yes there is more going on here
private MyTestObject myTestObject;
private MyTestObject spy;
private static final OtherObject VALID_OTHER_OBJECT = new OtherObject();
#Before
public void setup() {
this.spy = Mockito.spy(myTestObject);
}
#Test
public void ifOtherObjectIsNotNullExpectSubMethodToBeCalled() {
myTestObject.doSomething(VALID_OTHER_OBJECT, null);
verify(spy).someOtherMethod(VALID_OTHER_OBJECT, null);
}
I get a failing test and "Wanted but not invoked..." for someOtherMethod().
I jumped right into debug mode and checked. That method is called!
What could be the cause of this? Am I misusing the spy here?
Edit: I want to stretch that I know this is not what you typically test for, especially since someOtherMethod(...) has a non-void return-value here. But imagine the return value was void...
Basically I just want to understand why the spy fails here.
As per its Javadoc, Mockito.spy(object) creates a copy of the passed in object. Calling methods on the original passed in object then does not register on the spy, because the spy instance is not the same object.
Change myTestObject.doSomething(...) to spy.doSomething(...) and it should work.
Alternative (different way to achieve the same thing):
Consider using the #Spy annotation on your myTestObject.
Be sure to add MockitoAnnotations.initMocks(this); to your initialization method (in your junit test).
The #Before and #Mock annotations are useful as well.
I had one object creating another and that other object making calls. So I needed to make that internal object be using the spied reference instead. I used reflection and updated the reference using Whitebox.
TestAddressFragment fragment = spy(new TestAddressFragment());
AddressPresenter presenter = fragment.getPresenter();
Whitebox.setInternalState(presenter, "view", fragment );
Now my fragment could check if its method was called.
verify( fragment ).showAddress(any(), anyBoolean());
I have a jUnit test which tests one of my functions. In that function I make a call to another class's method which I want to mock using mockito. However, I can't seem to actually mock this. Here is what my jUnit test looks like:
#Test
public void testingSomething() throws Exception {
mock(AuthHelper.class);
when(new AuthHelper().authenticateUser(null)).thenReturn(true);
Boolean response = new MainClassImTesting().test();
assertTrue(response);
}
EDIT: In my MainClassImTesting().test() function that I'm calling, it makes a call to authenticateUser() and passes it a hashMap.
Mockito will allow you create a mock object and have its methods return expected results. So in this case, if you want the authenticateUser method of your mocked AuthHelper instance return true regardless of the value of the HashMap parameter, your code would look something like this:
AuthHelper mockAuthHelper = mock(AuthHelper.class);
when(mockAuthHelper.authenticateUser(any(HashMap.class))).thenReturn(true);
However, your mocked object is useless to your MainClassImTesting unless it has access or reference to it. You can achieve that by adding AuthHelper to the constructor of MainClassImTesting so that the class (including your test method) has access to it.
MainClassImTesting unitUnderTest = new MainClassImTesting(mockAuthHelper);
Boolean response = unitUnderTest.test();
assertTrue(response);
Or if your test method is the only method that needs AuthHelper, you can simply make AuthHelper a method parameter.
MainClassImTesting unitUnderTest = new MainClassImTesting();
Boolean response = unitUnderTest.test(mockAuthHelper);
assertTrue(response);
If you want to mock the function call for any parameter of type A, just do :
AuthHelper authHelper = Mockito.mock(AuthHelper.class);
Mockito.when(authHelper.authenticateUser(any(A.class))).thenReturn(true);
This is my sample service class:
class Service {
#Inject
private TestDao dao;
public void method() {
//Other logic
List<SomeClass> list = new ArrayList<SomeClass>();
privateMethod(list);
//Other logic
}
private void privateMethod(List<SomeClass> list) {
dao.save(list);
}
}
If I mock dao using Mockito, then how can I test the number of calls to dao.save method? When I tried with verify, I have to give the list object. But I am not seeing any way to get that object.
Any thoughts?
You can use the anyList() matcher if you don't care about exactly what list your method is being called with. For example, if you want to verify the save() method was called exactly thrice:
verify(dao, times(3)).save(anyList())
If you want to make further assertions about what list save() was called with, use ArgumentCaptor
An example usage of ArgumentCaptor:
ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(dao, times(3)).save(argument.capture());
List secondValue = argument.getAllValues().get(1); // captured value when the method was called the second time
Call verify with Matchers.anyList():
verify(dao).save(Matchers.anyList());