Sunday, March 6, 2016

Java : Mockito

Java : Mockito

Mockito is used for creating mock objects ie., creating Virtual methods for a class or interface before development happens and validating the result .

Below is a simple example of an interface Bulb Switch without implementation . We know that when press_on is pressed the bulb will turn on and vis versa .Below is the Junit test implementation

Example :

-----------------------------------------------------------------------
public interface Bulb_Switch {

    public String press_on();   
    public String press_off();
}

-----------------------------------------------------------------------
 import static org.mockito.Mockito.*;
import org.junit.*;

public class runner {
Bulb_Switch switch_on_off;

    @Before
    public void runner() {
        switch_on_off= mock(Bulb_Switch.class);  //'switch_on_off'= object , "Bulb_Switch"=Interface
        when(switch_on_off.press_on()).thenReturn("on");  //Designing return values for unimplemented methods
        when(switch_on_off.press_off()).thenReturn("on");  //Designing  return values
for unimplemented methods
    }
   
    @Test  // Positive test
    public void test1(){
        Assert.assertEquals("on", switch_on_off.press_on());  // Validating if the expected matches with return values
    }
   
    @Test //Negative test
    public void test2(){
        Assert.assertEquals("off", switch_on_off.press_off());// Validating if the expected matches with return values
    }
}

-----------------------------------------------------------------------  

Run as Junit test






Ref :
http://mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19      -- (Download jar)
http://luckyacademy.blogspot.in/2014/09/mockito-tutorial-part1.html
https://www.youtube.com/watch?v=ShO_Z64sGwI
https://www.youtube.com/watch?v=79eXGJ2rKZs
https://gojko.net/2009/10/23/mockito-in-six-easy-examples/

No comments:

Post a Comment