Junit Mockito example



//Mainclass: App
//We will mock the setName method in App class using Mockito

package mavenProjectJunitFrameworkTestcase.MavenProjectJunitFrameworkTestcase;

public class App
{
String name;
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
   
    //setName method used to set some value to class variable
    public String setName(String name) {
    return this.name=name;
    }
   
    //sum method is used to calculate sum of two variables
    public int sum(int a, int b) {
    int c = a+b;
    return c;
    }
}



Junit AppTest class:


package mavenProjectJunitFrameworkTestcase.MavenProjectJunitFrameworkTestcase;

import static org.junit.Assert.*;

import org.junit.Test;
import org.mockito.Mockito;

import junit.framework.Assert;

public class Apptest2 {
//Junit will not have main method. And classes with @Test annotations could be executed by //running as RunAs -> Junit test
@Test
public void testSetNameMethodusingMockito() {
          //This is to tell junit that we are going to mock methods of App class
App obj2 = Mockito.mock(App.class);
           //when method in Mockito will tell junit that which method we are mocking with  what //arguments, and will also give the mocked response
Mockito.when(obj2.setName("Srikanth")).thenReturn("srk");
Assert.assertEquals(obj2.setName("Srikanth"), obj2.name);
             //verify method in Mockito will tell whether mocked method is called with mocked response //is called or not
Mockito.verify(obj2).setName("Srikanth");
}


}

Comments

Popular posts from this blog

Notes on Junit

Use 'Assert.assertEquals' to test method using Junit framework