uk.org.thegatekeeper.dw.booking.BookingServiceIT.java Source code

Java tutorial

Introduction

Here is the source code for uk.org.thegatekeeper.dw.booking.BookingServiceIT.java

Source

/**
 * 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.dw.booking;

import org.apache.http.client.fluent.Request;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.org.thegatekeeper.Gate;
import uk.org.thegatekeeper.booking.service.PaymentService;
import uk.org.thegatekeeper.jdi.JdiGateController;
import uk.org.thegatekeeper.jdi.vm.SocketAttachingDebugger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;

public class BookingServiceIT {

    private SocketAttachingDebugger debugger;

    @Before
    public void before() throws Exception {
        debugger = new SocketAttachingDebugger();
        debugger.connect("localhost", 5005);
    }

    @After
    public void after() {
        debugger.disconnect();
    }

    @Test
    public void testConcurrentBooking() throws Exception {
        JdiGateController controller = new JdiGateController(debugger);
        Gate gate = controller.stopFirstThread().inClass(PaymentService.class).beforeMethod("pay").build();

        final List<Throwable> exceptions = new ArrayList<Throwable>();
        Thread booking = new Thread(new Runnable() {
            public void run() {
                try {
                    Request.Post("http://localhost:8080/booking/book/3/34").execute().returnContent().asString();
                } catch (Throwable t) {
                    exceptions.add(t);
                }
            }
        });

        booking.start();
        gate.waitFor(5, TimeUnit.SECONDS);

        String status = Request.Post("http://localhost:8080/booking/book/3/34").execute().returnContent()
                .asString();
        assertThat(status, containsString("\"success\":true"));

        gate.open();
        booking.join();

        assertEquals(1, exceptions.size());
    }
}