Monday, February 24, 2014

JMockit by Example

public class DBManager {
 public String retrieveAccountHolderName(int accountId) {
  String accountHolderName = null;

  // connect to db
  // retrieve the Account Holder Name

  return accountHolderName;
 }

 public static String getConnectionString() {
  return "ORIGINAL";
 }
}
public class Bank {
 DBManager dbManager = new DBManager();

 public String processAccount(int accountID) {

  // Some other code goes here

  String accountHolderName = dbManager
    .retrieveAccountHolderName(accountID);

  // some more processing code

  return accountHolderName;
 }

 public String getConnection() throws Exception {
  return "Connection";
  // some thing here might throw an exception
 }

 public String makeConnection() {
  // some connection related code
  // goes here

  // call to static method
  String conStr = DBManager.getConnectionString();

  // If the connection String
  // is anything other than
  // ORIGINAL return FAIL
  if (conStr.equals("ORIGINAL"))
   return "SUCCESS";
  else
   return "FAIL";
 }
}
import static org.junit.Assert.assertEquals;
import mockit.Expectations;
import mockit.Mocked;
import mockit.NonStrictExpectations;

import org.junit.Test;

public class BankTest {
 @Mocked
 DBManager dbManager; // variables declared here are mocked by default

 @Test
 public void testProcessAccount() {
  Bank bank = new Bank();

  // Define the Expectations block here
  new Expectations() {
   {
    dbManager.retrieveAccountHolderName(10);
    returns("Abhi");
   }
  };

  String name = bank.processAccount(10);

  assertEquals("Account holder Name for A/C id 10 is 'Abhi' ", "Abhi",
    name);
 }

 @Test
 public void testMakeConnection() {

  new NonStrictExpectations() {
   {
    DBManager.getConnectionString();
    returns("DUPLICATE");
   }
  };

  Bank bank = new Bank();
  String status = bank.makeConnection();

  assertEquals("Status is FAIL", "FAIL", status);
 }

 @Test(expected = Exception.class)
 public void testGetConnection() throws Exception {
  final Bank bank = new Bank();
  new Expectations(bank) {
   {
    bank.getConnection();
    result = new Exception();
   }
  };
  bank.getConnection();
 }

}

No comments:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...