Increment number after method is called Mockito - java

I have simple class with void method.
public class Simple {
public Void doSomething() {}
}
And I want to increment a number in my test after calling doSomething().
#Test
public void test1() {
int number = 0;
Simple simple = Mockito.mock(Simple.class);
Mockito.when(simple.doSomething()).then(number++);
}
Of course it is causing compilation error. How can I increment number after calling doSomething() ?
Alternative solution:
It's very bad practice but it's alternative solution for best answer below.
private int number = 0;
#Test
public void test1() {
Simple simple = Mockito.mock(Simple.class);
Mockito.when(simple.doSomething()).thenReturn(increment());
}
private Void increment() {
number++;
return null;
}

It is not clear from your question why you would want to have such a thing. The code in this answer is not good practice and I won't recommend it.
The first problem is that your method returns void so you can't stub it with Mockito.when. You need to use Mockito.doWhen.
In this code, I use Mockito.doAnswer to write a custom code inside the answer part:
#Test
public void test1() {
int[] number = { 0 };
Simple simple = Mockito.mock(Simple.class);
Mockito.doAnswer(new Answer<Void>() {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
number[0]++;
return null;
}
}).when(simple).doSomething();
}
The trick is to store the number inside a final variable (in this case, an array) and increment its only value in the answer part. Each time doSomething() will be called, it will be incremented and you will have the count inside number[0].
The same code can be made more compact with Java 8:
Mockito.doAnswer(invocation -> number[0]++).when(simple).doSomething();

Related

Is it possible to get StackOverflowError without recursion?

I have a task to get "StackOverflowError" in java without using -Xss and recursion. I really don't have ideas... Only some nonsense like generating huge java class at runtime, compile it and invoke...
Java stores primitive types on the stack. Objects created in local scope are allocated on the heap, with the reference to them on the stack.
You can overflow the stack without recursion by allocating too many primitive types in method scope. With normal stack size settings, you would have to allocate an excessive number of variables to overflow.
Here is the implementation of Eric J. idea of generating excessive number of local variables using javassist library:
class SoeNonRecursive {
static final String generatedMethodName = "holderForVariablesMethod";
#SneakyThrows
Class<?> createClassWithLotsOfLocalVars(String generatedClassName, final int numberOfLocalVarsToGenerate) {
ClassPool pool = ClassPool.getDefault();
CtClass generatedClass = pool.makeClass(generatedClassName);
CtMethod generatedMethod = CtNewMethod.make(getMethodBody(numberOfLocalVarsToGenerate), generatedClass);
generatedClass.addMethod(generatedMethod);
return generatedClass.toClass();
}
private String getMethodBody(final int numberOfLocalVarsToGenerate) {
StringBuilder methodBody = new StringBuilder("public static long ")
.append(generatedMethodName).append("() {")
.append(System.lineSeparator());
StringBuilder antiDeadCodeEliminationString = new StringBuilder("long result = i0");
long i = 0;
while (i < numberOfLocalVarsToGenerate) {
methodBody.append(" long i").append(i)
.append(" = ").append(i).append(";")
.append(System.lineSeparator());
antiDeadCodeEliminationString.append("+").append("i").append(i);
i++;
}
antiDeadCodeEliminationString.append(";");
methodBody.append(" ").append(antiDeadCodeEliminationString)
.append(System.lineSeparator())
.append(" return result;")
.append(System.lineSeparator())
.append("}");
return methodBody.toString();
}
}
and tests:
class SoeNonRecursiveTest {
private final SoeNonRecursive soeNonRecursive = new SoeNonRecursive();
//Should be different for every case, or once generated class become
//"frozen" for javassist: http://www.javassist.org/tutorial/tutorial.html#read
private String generatedClassName;
#Test
void stackOverflowWithoutRecursion() {
generatedClassName = "Soe1";
final int numberOfLocalVarsToGenerate = 6000;
assertThrows(StackOverflowError.class, () -> soeNonRecursive
.createClassWithLotsOfLocalVars(generatedClassName, numberOfLocalVarsToGenerate));
}
#SneakyThrows
#Test
void methodGeneratedCorrectly() {
generatedClassName = "Soe2";
final int numberOfLocalVarsToGenerate = 6;
Class<?> generated = soeNonRecursive.createClassWithLotsOfLocalVars(generatedClassName, numberOfLocalVarsToGenerate);
//Arithmetic progression
long expected = Math.round((numberOfLocalVarsToGenerate - 1.0)/2 * numberOfLocalVarsToGenerate);
long actual = (long) generated.getDeclaredMethod(generatedMethodName).invoke(generated);
assertEquals(expected, actual);
}
}
EDIT:
The answer is incorrect, because it is one type of recursion. It is called indirect recursion https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion.
I think the simplest way to do this without recursion is the following:
import java.util.LinkedList;
import java.util.List;
interface Handler {
void handle(Chain chain);
}
interface Chain {
void process();
}
class FirstHandler implements Handler {
#Override
public void handle(Chain chain) {
System.out.println("first handler");
chain.process();
}
}
class SecondHandler implements Handler {
#Override
public void handle(Chain chain) {
System.out.println("second handler");
chain.process();
}
}
class Runner implements Chain {
private List<Handler> handlers;
private int size = 5000; // change this parameter to avoid stackoverflowerror
private int n = 0;
public static void main(String[] args) {
Runner runner = new Runner();
runner.setHandlers();
runner.process();
}
private void setHandlers() {
handlers = new LinkedList<>();
int i = 0;
while (i < size) {
// there can be different implementations of handler interface
handlers.add(new FirstHandler());
handlers.add(new SecondHandler());
i += 2;
}
}
public void process() {
if (n < size) {
Handler handler = handlers.get(n++);
handler.handle(this);
}
}
}
At first glance this example looks a little crazy, but it's not as unrealistic as it seems.
The main idea of this approach is the chain of responsibility pattern. You can reproduce this exception in real life by implementing chain of responsibility pattern. For instance, you have some objects and every object after doing some logic call the next object in chain and pass the results of his job to the next one.
You can see this in java filter (javax.servlet.Filter).
I don't know detailed mechanism of working this class, but it calls the next filter in chain using doFilter method and after all filters/servlets processing request, it continue working in the same method below doFilter.
In other words it intercepts request/response before servlets and before sending response to a client.It is dangerous piece of code because all called methods are in the same stack at the same thread. Thus, it may initiate stackoverflow exception if the chain is too big or you call doFilter method on deep level that also provide the same situation. Perhaps, during debugging you might see chain of calls
in one thread and it potentially can be the cause of stackoverflowerror.
Also you can take chain of responsibility pattern example from links below and add collection of elements instead of several and you also will get stackoverflowerror.
Links with the pattern:
https://www.journaldev.com/1617/chain-of-responsibility-design-pattern-in-java
https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
I hope it was helpful for you.
Since the question is very interesting, I have tried to simplify the answer of hide :
public class Stackoverflow {
static class Handler {
void handle(Chain chain){
chain.process();
System.out.println("yeah");
}
}
static class Chain {
private List<Handler> handlers = new ArrayList<>();
private int n = 0;
private void setHandlers(int count) {
int i = 0;
while (i++ < count) {
handlers.add(new Handler());
}
}
public void process() {
if (n < handlers.size()) {
Handler handler = handlers.get(n++);
handler.handle(this);
}
}
}
public static void main(String[] args) {
Chain chain = new Chain();
chain.setHandlers(10000);
chain.process();
}
}
It's important to note that if stackoverflow occurs, the string "yeah" will never be output.
Of course we can do it :) . No recursion at all!
public static void main(String[] args) {
throw new StackOverflowError();
}
Looking at this answer below, not sure if this works for Java, but sounds like you can declare an array of pointers? Might be able to achieve Eric J's idea without requiring a generator.
Is it on the Stack or Heap?
int* x[LARGENUMBER]; // The addresses are held on the stack
int i; // On the stack
for(i = 0; i < LARGENUMBER; ++i)
x[i] = malloc(sizeof(int)*10); // Allocates memory on the heap

Mockito : Testing void methods gives InvalidUseOfMatchersException

I'm having problems with two void methods. In encouragedVenturesScoring I've followed this answer mocking an arraylist that will be looped in a for loop and haven't mocked the list, but passed a real list and added mocked objects.
Mockito gives me an InvalidUseOfMatchersException on this line
verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
There are lots of questions on SO on this exception , and I think it's because of anyInt(). Anyway I changed it to
verify(effectList.get(0)).execute(playerHandler);
And now it's saying Wanted but not invoked effect.execute(playerHandler)
Actually there were zero interactions with this mock
Is it because I put doNothing ?
doNothing().when(effect).execute(playerHandler);
In my second method militaryStrengthScoring() method is there a way to skip the first chunk of code and just test the if..else condition? What would be the best approach to test this method?
Thank you for your time.
This is the class to be tested
public class EndGameScoringBaseController implements EndGameScoringHandler {
private static final int[] TERRITORIES_REWARD = {0,0,1,4,10,20};
private static final int[] CHARACTERS_REWARD = {1,3,6,10,15,21};
private static final int RESOURCES_RATE = 5;
private static final int FIRST_MILITARY_REWARD = 5;
private static final int SECOND_MILITARY_REWARD = 2;
private PlayerHandler player;
public EndGameScoringBaseController(PlayerHandler player) {
super();
this.player = player;
}
#Override
public void encouragedVenturesScoring() {
for (DevelopmentCard card : player.getPlayer().getPersonalBoard().getVentures()) {
for (Effect e : card.getPermanentEffects())
e.execute(player);
}
}
#Override
public void militaryStrengthScoring(GameController game) {
Set<Integer> points = new HashSet<>();
int myPoints = this.player.getPointsHandler().getMilitaryPoints();
for (PlayerHandler p: game.getPlayers()) {
points.add(p.getPointsHandler().getMilitaryPoints());
}
int[] rank = new int[points.size()];
int j = 0;
for (Integer i : points) {
rank[j] = i;
j++;
}
Arrays.sort(rank);
if (rank[rank.length-1] == myPoints) {
player.getPointsHandler().winMilitaryPoints(FIRST_MILITARY_REWARD);
}
else if (rank[rank.length-2] == myPoints) {
player.getPointsHandler().winVictoryPoints(SECOND_MILITARY_REWARD);
}
}
Tested method for encouragedVenturesScoring
#Test
public void encouragedVenturesScoringTest() {
//given
List<DevelopmentCard> ventureList;
ventureList = Arrays.asList(developmentCard, developmentCard);
when(playerHandler.getPlayer().getPersonalBoard().getVentures()).thenReturn(ventureList);
List<Effect> effectList;
effectList = Arrays.asList(effect, effect);
when(developmentCard.getPermanentEffects()).thenReturn(effectList);
doNothing().when(effect).execute(playerHandler);
//when
endgameController.encouragedVenturesScoring();
//then
verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
}
Incomplete tested method for militaryStrengthScoring
#Test
public void militaryStrengthScoringTest() {
//given
when(playerHandler.getPointsHandler().getMilitaryPoints()).thenReturn(4);
doNothing().when(playerHandler.getPointsHandler()).winMilitaryPoints(FIRST_MILITARY_REWARD);
//when
endgameController.militaryStrengthScoring(gameController);
//then
/../
}
You're right that this is the problem:
verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
Mockito only allows for calls like any() and anyInt() to stand in for parameters to the mock themselves, due to the internal implementation of matchers.
/* OK */ when(yourMock.yourMethod(anyInt())).thenReturn(42);
/* BAD */ when(yourList.get(anyInt()).yourMethod(0)).thenReturn(42);
/* OK */ verify(yourMock).yourMethod(anyInt());
/* BAD */ verify(yourList.get(anyInt())).yourMethod(0);
The failure with get(0) is likely an actual failure, and may be related to the fact that your encouragedVenturesScoringTest is actually not calling encouragedVenturesScoring, it's calling influencedCharactersScoring. If this continues to give you trouble after fixing that error, in ways related to Mockito, please edit your question.
You can only verify mock objects created by Mockito.
But effectList is a "real" list. Therefore Mockito knows nothing about that object. Thus any attempt to verify that list must fail.
If you want to verify that object - then you have to mock it!
Of course, this means that you have specify all calls that will go to the mocked list.

Getting number of calls to a mock

Assume I want to test code like this:
class ClassToTest
// UsedClass1 contains a method UsedClass2 thisMethod() {}
UsedClass1 foo;
void aMethod()
{
int max = new Random().nextInt(100);
for(i = 0; i < max; i++)
{
foo.thisMethod().thatMethod();
}
}
}
If I have a test like this:
ClassToTest test;
UsedClass1 uc1;
UsedClass2 uc2;
#Test
public void thingToTest() {
test = new ClassToTest();
uc1 = mock(UsedClass1.class);
uc2 = mock(UsedClass2.class);
when(uc1.thisMethod()).thenReturn(uc2);
when(uc2.thatMethod()).thenReturn(true);
test.aMethod();
// I would like to do this
verifyEquals(callsTo(uc1.thisMethod()), callsTo(uc2.thatMethod()));
}
How can I get the number of calls to uc1.thisMethod() and uc2.thatMethod() so I can check they were both called the same number of times?
You can do something like this:
YourService serviceMock = Mockito.mock(YourService.class);
// code using YourService
// details of all invocations including methods and arguments
Collection<Invocation> invocations = Mockito.mockingDetails(serviceMock).getInvocations();
// just a number of calls of any mock's methods
int numberOfCalls = invocations.size();
If you want only the invocations of certain method/param combination you, you can do so with
int specificMethodCall = Mockito.mockingDetails(serviceMock.myMethod(myParam)).getInvocations()
You could stub your methods, and increment a counter, like this:
final AtomicInteger countCall1 = new AtomicInteger();
Mockito.doAnswer(new Answer<UsedClass2>() {
#Override
public UsedClass2 answer(InvocationOnMock invocation) throws Throwable {
countCall1.incrementAndGet();
return uc2;
}
}).when(uc1).thisMethod();
If you know the number of times a method is suppoed to be called you can use the times() method of Mockito
//for example if had to be called 3 times
verify(uc1, times(3)).thisMethod();
verify(uc2, times(3)).thatMethod();
However, I now see that you call the method a random number of times, so this probably isn't the best answer unless you stub out the random number generator to always return an expected value.
You can use a custom VerificationMode to count the invocations, here you go:
public class InvocationCounter {
public static <T> T countInvocations(T mock, AtomicInteger count) {
return Mockito.verify(mock, new Counter(count));
}
private InvocationCounter(){}
private static class Counter implements VerificationInOrderMode, VerificationMode {
private final AtomicInteger count;
private Counter(AtomicInteger count) {
this.count = count;
}
public void verify(VerificationData data) {
count.set(data.getAllInvocations().size());
}
public void verifyInOrder(VerificationDataInOrder data) {
count.set(data.getAllInvocations().size());
}
#Override
public VerificationMode description(String description) {
return VerificationModeFactory.description(this, description);
}
}
}
And then use it like this (works also with void return types):
#Mock
private Function<String, Integer> callable;
AtomicInteger count= new AtomicInteger(); //here is the actual invocation count stored
countInvocations(callable,count).apply( anyString());
assertThat(count.get(),is(2));

java question to decide who called this method

I have the following scenario where
both testOne() and testTwo calls same callMe() method.
How do I decide inside callMe() method who called callMe().
public void testOne(){
callMe();
}
public void testTwo(){
callMe();
}
public void callMe(){
System.out.println("I was called by following method."+methodName);
}
Any sort of help is appreciated.
Any solution that has you generating a stacktrace and looking at the second frame is one that is going to lead to pain - what you are essentially doing is bypassing the idea of passing what a function needs to it in order for the function to do it's work.
If you need the name of the caller method, then just pass it as a parameter. If you need some other piece of data to decide what to do in the callMe() method, pass it (as a boolean, int, etc.).
It will confuse other developers working on your code why callMe() has what are essentially secret parameters.
public void testOne(){
callMe("testOne");
}
public void testTwo(){
callMe("testTwo");
}
public void callMe(String methodName){
System.out.println("I was called by following method."+methodName);
}
My best answer is to query the stack trace.
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String previousMethodName = null;
for (int i = 0; (i < stackTrace.length) && (previousMethodName == null); i++)
{
if (stackTrace[i].getMethodName().equals("callMe") && (i < stackTrace.length - 1))
{
previousMethodName = stackTrace[i + 1].getMethodName();
}
}
if (previousMethodName != null)
{
System.out.println("Previous method = " + previousMethodName);
}
sorry, i meant to answer your question and not comment :( so here it is
i think this already answered question may help you out: Get current stack trace in Java
The simplest approach is to use a parameter
public static void testOne(){
callMe("testOne");
}
public static void testTwo(){
callMe("testTwo");
}
public static void callMe(){
System.out.println("I was called by following method."+methodName);
}
However, you can use the call stack.
public static void callMe(){
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
System.out.println("I was called by following method."+methodName);
}

How to test an int has been incremented using Junit?

I have the following method that I would like to test, it simply increments an int if a Boolean condition is true:
public void incrementIfConditionMet(Boolean personCheckedIn) {
int peopleInHotel=0;
if (personCheckedIn==true){
peopleInHotel++
}
}
I am very new to unit testing in Java. How can I unit test this to check if the int has been incremented or not?
Currently your value of peopleInHotel cannot be accessed outside the method, as it was created internally. If you want to access it, you should do the following:
private int peopleInHotel=0;
public int getPeopleInHotel() {
return peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn){
peopleInHotel++
}
}
Now in your test class, you can check by calling getPeopleInHotel();
So the test case would be:
int initalValue = classInstance.getPeopleInHotel();
classInstance.incrementIfConditionMet(true);
assertEquals(classInstance.getPeopleInHotel(), initalValue +1);
This would also fix your issue where you don't keep the value once the method has been ran. At the moment, in your current code setup, your variable of peopleInHotel is discarded after you've finished with the method.
int peopleInHotel=0;
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
public int getPeopleInHotel() { //test the returned value after you've incremented
return peopleInHotel;
}
Try like this:
public class Hotel {
private int peopleInHotel = 0;
//a constructor...
public int getPeopleInHotel() {
return this.peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
}
In your Unit-Test, you now can do something like that:
//defining your TestCase
Hotel hotel = new Hotel();
int initValue = hotel.getPepleInHotel();
hotel.incrementIfconditionmet(true);
assertEquals(hotel.getPeopleInHotel(),initValue+1);

Categories