Java tutorial
/** * Copyright 2014 Andy Godwin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.thegatekeeper.sa.booking; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import uk.org.thegatekeeper.Gate; import uk.org.thegatekeeper.aop.AopGateController; import uk.org.thegatekeeper.booking.dao.SeatAlreadyBookedException; import uk.org.thegatekeeper.booking.model.Seat; import uk.org.thegatekeeper.booking.service.BookingService; import uk.org.thegatekeeper.booking.service.PaymentService; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/booking-context.xml", "/booking-test-context.xml" }) public class BookingServiceTest { @Inject private BookingService bookingService; @Inject private AopGateController gateController; @Test public void checkConcurrentBookingsForTheSameSeatUsingGates() throws Exception { Gate gate = gateController.stopFirstThread().inClass(PaymentService.class).beforeMethod("pay").build(); final List<Throwable> exceptions = new ArrayList<>(); final Seat seat = new Seat(4, 12); Thread fred = new Thread(new Runnable() { @Override public void run() { try { bookingService.book(seat); } catch (Throwable t) { exceptions.add(t); } } }); fred.start(); gate.waitFor(2, TimeUnit.SECONDS); assertTrue(bookingService.book(seat)); gate.open(); fred.join(); assertEquals(1, exceptions.size()); assertTrue(exceptions.get(0) instanceof SeatAlreadyBookedException); } }