public class MockExample extends TestCase {

	private StockItem cabbage;

	private StockItem banana;

	private List<StockItem> stockItems;

	private Sale sale;

	@Override
	protected void setUp() {
		cabbage = new StockItem();
		cabbage.setId(new Long(0));
		cabbage.setName("Kapsad");
		cabbage.setPrice(new BigDecimal(5.50));
		cabbage.setQuantity(new Integer(3));

		banana = new StockItem();
		banana.setId(new Long(1));
		banana.setName("Banaanid");
		banana.setPrice(new BigDecimal(7.50));
		banana.setQuantity(new Integer(6));

		stockItems = new ArrayList<StockItem>();
		stockItems.add(cabbage);
		stockItems.add(banana);

		Client customer = new Client();
		customer.setId(new Long(1));
		customer.setFirstName("Toomas");
		customer.setLastName("Kahur");
		customer.setDiscountPercentage(new Integer(1));

		sale = new Sale();
		sale.addItem(cabbage);
		sale.setClient(customer);
	}

	public void testRegisterSale() {
		// Prepare Mocks
		// mock for quering stock item by id
		Query stockItemQueryMock = createMock(Query.class);

		// create mock Session object...
		Session sessionMock = createMock(Session.class);

		// and also mock Transaction object...
		Transaction transactionMock = createNiceControl().createMock(
				Transaction.class);

		// assign fake session to HibernateUtil
		HibernateUtil.setSession(sessionMock);

		SalesDomainController controller = new SalesDomainControllerImpl();

		// record invocations
		expect(sessionMock.beginTransaction()).andReturn(transactionMock);
		expect(sessionMock.createQuery("from StockItem where id=?")).andReturn(
				stockItemQueryMock).once();
		expect(stockItemQueryMock.setLong(0, cabbage.getId())).andReturn(
				stockItemQueryMock).once();
		expect(stockItemQueryMock.list()).andReturn(
				Arrays.asList(new StockItem[] { cabbage })).once();
		sessionMock.update(cabbage);
		expect(sessionMock.save(sale)).andReturn(sale.getId()).once();
		transactionMock.commit();
		sessionMock.clear();

		// mark for replay
		replay(transactionMock);
		replay(sessionMock);
		replay(stockItemQueryMock);

		// start invocation
		controller.registerSale(sale);

		// verify
		verify(transactionMock);
		verify(sessionMock);
		verify(stockItemQueryMock);

		assertNotNull(sale.getSellingTime());
		assertEquals(new Integer(0), cabbage.getQuantity());
	}

}

edit