Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, September 5, 2021

Unit testing with Mockito in Java

Word definitions taken from:
https://stackoverflow.com/questions/346372/whats-the-difference-between-faking-mocking-and-stubbing

  • Stub - an object that contains predefined answers to methods
  • Mock - an object made to satisfy the expected outcome, just like a dummy
  • Fake - an object with a minimum necessary implementation/ return value for a test

Mocking a class

SomeClass someClass = mock(SomeClass.class);
// this creates a mock of a class. but it won't perform any responsibility of that class

Sample class for this tutorial, 'MyClass'

class MyClass {
    public MyClass(S
omeService someService, AnotherClass anotherClass) {
        this.
someService = someService:
        this.anotherClass = anotherClass:
 
  
}
}

We can easily mock these kind of constructor parameters using @Mock annotation

@Mock
SomeService someService;

@Mock
AnotherClass anotherClass;

MyClass myClass;

private initTests() {
    myClass = new MyClass(
someService, anotherClass);
}


If  the class MyClass contains a function defined below,

public String getStudentName () {
    SomeClass someClass = someService.getThatObject();
    Student student = someClass.getStudent();
    return student.getName(); 
}

We can simply test it like below (this is just to understand the concepts, and not the only possible way to test)

@Test
function testGivenWhenThenSomeTestFunctionName () {
    SomeService someService = mock(SomeService.class);
    SomeClass someClass = mock(SomeClass.class);
    Student student = mock(Student.class);
    when( someService.getThatObject() ).thenReturn(someClass);
    when( someClass.getStudent() ).thenReturn(student);
    when( student.getName() ).thenReturn("expectedStringValue");
 
    String result = myClass.getStudentName();
    assertEquals(result, "expectedStringValue"); 
}
 

we can test the same function like below too, without mocking intermediate results

@Test
function testGivenWhenThenSomeTestFunctionName () {
    SomeService someService = mock(SomeService.class);
    SomeClass someClass = mock(SomeClass.class);
    when( someService.getThatObject() ).thenReturn(someClass);
    when( someClass.getStudent() ).thenReturn(student);
    when( someClass.getStudent().getName() ).thenReturn("expectedStringValue");
 
    String result = myClass.getStudentName();
    assertEquals(result, "expectedStringValue"); 
}

even we can use deep stubs to test the above function

@Test
// @TODO: verify this working
function testGivenWhenThenSomeTestFunctionName () {
    SomeService someService = mock(SomeService.class);
    Student student = mock(Student.class, Mockito.RETURNS_DEEP_STUBS);
    SomeClass someClass = mock(SomeClass.class, Mockito.RETURNS_DEEP_STUBS);
     
    student.setName("expectedStringValue");
    someClass.setStudent(student);

    when( someService.getThatObject() ).thenReturn(someClass);

    String result = myClass.getStudentNam();
    assertEquals(result, "expectedStringValue"); 
}


@TODO:
catching expected exceptions

@TODO:
calling real implementation

@TODO:
stub private/protected methods


Saturday, November 21, 2020

Java basics - part 1

This is the very beginning of a JAVA programming series, which covers basics, important points regarding sequence, selection, iteration, std in, std out, and lot more.

This post contains some important thins regarding Java language, and most of them are coming as learning outcomes from "Hackerrank" Java problem solving.

Std Input

import scanner class

import java.util.Scanner;
 
Then use like below 

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
String s = scan.nextLine();
 
do{
String st1=scan.nextLine();

System.out.println(count + " " + st1);
count += 1;
}while(
scan.hasNext());

while(
scan.hasNext()){
// String st1=scan.nextLine();
st1 =
scan.nextLine();
System.out.println(count + " " + st1);
count += 1;
 
scan.close();
 

Std Output

Use standard output to send to terminal
 
System.out.println("String val: " + stringVariable );
System.out.println("Double val: " + Double.toString(doubleVariable) );
System.out.println("Integer val: " + Integer.toString(integerValue) );
 
 

If - else if - else, Switch, shorthand if  

// if - else if - else
if(intVar > 100){
    System.out.println(">100");
}
else if(intVar >= 80){
    System.out.println(">=80");
}
else{
    System.out.println("<80");
}
 
// shorthand
resultVar = (intVar > 100) ? ">100" : ( (intVar >= 80) ? ">=80" : "<80" );
System.out.println(resultVar);
 
// switch - case
switch(someInteger){
    case 1:
        System.out.println("equals 1");
        break;
    case 2:
        System.out.println("equals 2");
        break;
    case 5:
        System.out.println("equals 5");
        break;
    default:
        System.out.println("default value");
}
 

formatting output with printf

// 15 chars left is a string, right aligning integer with 3 digits
System.out.printf("%-15s%03d\n", stringVar, intVar);
 

Type casting

// double to int 
int var1 = (int)( Math.pow(2, c)*b ); 
int var1 = new Double(Math.pow(2, c)*b).intValue() 
 
// int to String
String var3 = Integer.toString(intValue);
String var4 = String.valueOf(intValue);
 
// String to char array
char[] arr = stringVar.toCharArray(); 
 

Static Initializer

public class Javaclass{
    static boolean flag = false;
    static int B=0;
 
    // this part executes before the main method
    static {
        System.out.print("Inside static initializer");
     Scanner sc = new Scanner(System.in);
    B = sc.nextInt();
  flag = true;
    }
 
    public static void main(String[] args){
        if(flag){
            // do something
        }
    
 

Currency formatting

create a NumberFormat 
NumberFormat cf 
 
If currency for your locale is available, get it 
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US) 
 
or create a new locale
Locale my_locale = new Locale("en", "LK"); // LK for Sri Lanka, extended from "en"
NumberFormat nf = NumberFormat.getCurrencyInstance(my_locale);
 
Then use the NumberFormat to print double value as a currency
double doubleValue = 20.3; // 0.22, 40, 2,45
System.out.print( nf.format(doubleValue) );
 

Probable Prime

BigInteger bigIntInstance = new BigInteger(n);
boolean isPrime = bigIntInstance.isProbablePrime(1);
 
Let's meet with the next post
Thanks for the reading