Java tutorial
package com.conwet.xjsp.session; /* * #%L * eXtensible JSON Streaming Protocol * %% * Copyright (C) 2011 - 2014 CoNWeT Lab., Universidad Politcnica de Madrid * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import com.conwet.xjsp.errors.ConnError; import org.json.simple.JSONObject; import com.conwet.xjsp.errors.ConnectionException; import org.json.simple.parser.JSONParser; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; import static org.assertj.core.api.Assertions.*; /** * * @author sortega */ public class ConnectionContextTest { private ConnectionContext instance; private ConnectionState state; private MockedSocketChannel channel; @Before public void before() { this.state = mock(ConnectionState.class); this.instance = new ConnectionContext(state); this.channel = new MockedSocketChannel(); instance.setChannel(channel); } @Test public void shouldSendErrorOnConnectionException() throws Exception { System.out.println("should send error on connection exception"); doThrow(new ConnectionException(ConnError.InvalidMessage, "Message")).when(state).newData(instance); instance.start(); instance.newData("hello"); JSONObject errorMessage = (JSONObject) new JSONParser().parse(channel.getBufferAsString()); assertThat(errorMessage.get("type")).isEqualTo("xjsp:error"); JSONObject errorPayload = (JSONObject) errorMessage.get("message"); assertThat(errorPayload.get("code")).isEqualTo(400L); assertThat(errorPayload.get("message")).isEqualTo("Invalid message: Message"); } @Test public void shouldDisposeBeIdempotent() throws Exception { channel = mock(MockedSocketChannel.class); instance.setChannel(channel); instance.start(); instance.dispose(); verify(state).start(instance); verify(state).abort(instance); verify(channel).close(); // check idempotence instance.dispose(); verifyNoMoreInteractions(channel); verifyNoMoreInteractions(state); } }