My favorites | Sign in
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
mockito  
Updated Jul 14, 2015 by luis.d.c...@gmail.com

package com.mgl.wrap.caps.enterprise.service;

import java.util.List;

import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.;

public class Mockito {

@Mock List
<string>
mockedList;

@Before public void setup(){
MockitoAnnotations.initMocks(this);
}
@Test public void mockito(){
//mock creation //List
<string>
mockedList = mock(List.class);

//using mock object mockedList.add("one"); mockedList.clear();
//verification verify(mockedList).add("one"); verify(mockedList).clear();

//stubbing when(mockedList.get(0)).thenReturn("first", "second", "third"); when(mockedList.get(1)).thenThrow(new RuntimeException());
//this will override all settings from above //when(mockedList.get(anyInt())).thenReturn("element");
//following prints "first" System.out.println(mockedList.get(0)); System.out.println(mockedList.get(0)); System.out.println(mockedList.get(0));

//following throws runtime exception try{
mockedList.get(1);
}catch(Exception e){
System.out.println("Exception");
}

//following prints "null" because get(999) was not stubbed System.out.println(mockedList.get(999));
mockedList.add("once");

mockedList.add("twice"); mockedList.add("twice");
mockedList.add("three times"); mockedList.add("three times"); mockedList.add("three times");
//following two verifications work exactly the same - times(1) is used by default verify(mockedList).add("once"); //times(1) is the default. Therefore using times(1) explicitly can be omitted. verify(mockedList, times(1)).add("once");
//exact number of invocations verification verify(mockedList, times(2)).add("twice"); verify(mockedList, times(3)).add("three times");
//verification using never(). never() is an alias to times(0) verify(mockedList, never()).add("never happened");
//verification using atLeast()/atMost() verify(mockedList, atLeastOnce()).add("three times"); //verify(mockedList, atLeast(2)).add("five times"); verify(mockedList, atMost(5)).add("three times");

reset(mockedList); //at this point the mock forgot any interactions & stubbing
//verify(mock, timeout(100).times(2)).someMethod(); //verify(mock, description("This will print on failure")).someMethod();
}
}

Powered by Google Project Hosting