How to Mock recursive function - junit

When I test a method the inner of the method invokes itself and another method that is in the same class. I use a partial mock to specify the other method's return value but how do I specify the first method's return value?

If you are mocking the method, then it is no longer recursive - because the mock will only return the final return value that would be returned after recursion.
If you want to test the recursive function, then don't mock the recursive method.
Your explanation is a little unclear, but perhaps just mocking the other method that is called is sufficient for your test. You can make sure that other method gets called with the correct parameters.

lets try returnsMany in mockk:
coEvery{ mockEntity.recursiveMethod()}.returnsMany(value1, value2,...)
The first call recursiveMethod() will return value1, then the second call return value2,...
Handle your recursive flow in the right way

Related

Are Method Call and Method execution different things?

I did see this post: Method invocation vs method execution but to me it does not quite make sense. I thought in order to execute the method, we must call the method, but both are two separate things in my opinion. The execution of the method is separate thing than the method call itself. I am unable to see how they are the same thing.
I think you're overthinking about it.
Calling a method or a method getting executed are the exact same thing.
Or you could say, a method gets executed when it gets called.
Eg:
calling the method here
int x = returnThatInteger();
some where else in the code
public int returnThatInteger(){ // method executing here
return 1;
}
So you're right,
in order to execute the method, we must call the method

Calling mock method instead of real method with Mockito

I have a method which needs to be called instead of the real method.
Instead I get an exception. Can somebody please help me with right way to call the alternate method through mockito ?
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 4 recorded.
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
//Code starts here
class A{
public realMethod(String s, Foo f){
}
}
class B {
public mockMethod(String s, Foo f) {
}
}
class UnitTestClass{
ClassA mock = new ClassA();
mock.when(realMethod(any(String.class), any(Foo.class))).thenReturn(mockMethod(any(String.class),any(Foo.class));
}
You are getting mocking wrong.
Here:
thenReturn(mockMethod(any(String.class),any(Foo.class));
That simply doesn't make sense.
Mocking works like this:
you create a mock object of some class, like A mock = mock(A.class)
you specify interactions on that mock object
Your code implies that you think that these specifications are working like "normal" code - but they do not!
What you want to do: when some object is called with certain parameters, then return the result of another method call.
Like in:
when(a.foo(x, y)).thenReturn(b.bar(x, y))
That is what want you intend to do. But thing is: it isn't that easy. You can't use the any() matcher in thee thenReturn part in order to "provide" the arguments that were passed in the when() call before! It is that simply.
Mocking should be within a specific unit test to get a specific result.
Meaning: you are not writing an ordinary program where it would make any sense to "forward" parameters to another call. In other words; your code should more look like:
when(mock.realMethod("a", someSpecificFoo)).thenReturn(mockMethod("a", someSpecificFoo))
That is the only thing possible here.
Beyond that, you might want to look into a Mockito enter link description here instead.
Long story short: it simply looks like you don't understand how to use mocking frameworks. I suggest that you step back and read/work various tutorials. This is not something you learn by trial and error.

powermockito static and non static method chain

I want non-static method of an object returned by a static factory method to return a specific result.
After I have done this setup my test code will be calling the ConnectionFactory.getConn("ABC") indirectly through another piece of code which is being tested.
PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);
I get a NPE for the above statement.
I already have #PrepareForTest({FXAllConnectionFactory.class, ConnectionStatus.class}) at the beginning of my junit test class.
What would be the correct way of doing it?
Thanks in advance :)
I guess there is no point in creating a fluent/chained call for your test setup.
You see:
PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);
is probably meant to configure two calls:
ConnectionFactory.getConn("ABC") and then
getCurrentStatus() on the result of that first call
And what makes you think that PowerMockito magically knows what should be returned by that first call to getConn()?
In other words:
First provide a mocked Connection object X; and configure your mocks so that getConn() returns that object
In addition to that, you have to configure X to return the desired value upon a call to getCurrentStatus() ... on X!
So, the answer is actually: what you want to do isn't possible. The idea is; you specify behavior such as:
when A.foo() is called; then return some X
There is no magic power within PowerMockito to turn
when A.foo().bar() is called thren return Y
into
when A.foo() is called, return X; when X.bar() is called return Y
You have to specify that step by step.

How to make a void protected method return response in Junits

How to mock a void protected Method in a filter using mockito and make it return some "response"
since it's a void method ,i cannot use doReturn(some value) ,is there a way to set a response and make
it return that.
The short answer is that you can't, the long answer is that even if you could, you shouldn't.
The purpose of your test should be to verify the behaviour of your class/method. What does your filter do? What are the possible paths through the code? It must either return a value, have a side-effect or communicate with another object. These are the things that you should be testing for.
For example, seeing as this is a filter chain I assume that it's going to apply some logic and either call the next filter or not. You should mock the next filter in the chain and assert that it's called correctly or not depending on your logic.
I don't think we can return any response from methods that returns void but in case if we want to mock a method that returns void we could use:
Mockito.doNothing().when(apiService).methodNamethatReturnsVoid(Mockito.anyString();

mockito when thenReturn does not return stubbed array list

List<Populate> fullAttrPopulateList = getFullAtrributesPopulateList(); //Prepare return list
when(mockEmployeeDao.getPopulateList(null)).thenReturn(fullAttrPopulateList);
MyDTO myDto = testablePopService.getMyPopData(); //Will call mockEmployeeDao.getPopulateList(null)
//verify(mockEmployeeDao,times(1)).getPopulateList(null);
assertEquals(fullAttrPopulateList.size(), myDto.getPopData().size()); //This fails because myDto.getPopData().size() returns 0
As you can see testablePopService.getMyPopData() calls mockEmployeeDao.getPopulateList(null) but when I debug it a zero sized list returns instead of the stubbed array list which is prepared by getFullAtrributesPopulateList();
If I uncomment the verify statement, it passes the test meaning getPopulateList(null) behavior does get called.
Can anyone give me some advice why my stubbed array list cannot be returned even it is verified the expected behavior happened? How come an empty array list returns rather than a null if I did something wrong?
First, check that the method is non-final and visible throughout its hierarchy. Mockito can have trouble mocking methods that are hidden (e.g. overriding a package-private abstract class's implementation); also, Mockito is entirely unable to mock final methods, or even to detect that the method is final and warn you about it.
You may also want to check that your call is using the overload you expect. Mockito's default list return value is an empty list, so you may simply stubbing one method and seeing the default value for another. You can see which method interactions Mockito has added by adding a call to verifyZeroInteractions temporarily, and Mockito will throw an exception with a list of calls that mock has received. You could also add verifyNoMoreInteractions, and even leave it in there, at the expense of test brittleness (i.e. the test breaks when the actual code continues to work).