|
| 1 | +package com.hoho.android.usbserial.util; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | +import static org.mockito.Mockito.mock; |
| 5 | +import static org.mockito.Mockito.when; |
| 6 | + |
| 7 | +import android.hardware.usb.UsbEndpoint; |
| 8 | +import android.os.Process; |
| 9 | + |
| 10 | +import com.hoho.android.usbserial.driver.CommonUsbSerialPort; |
| 11 | + |
| 12 | +import org.junit.Test; |
| 13 | + |
| 14 | +public class SerialInputOutputManagerTest { |
| 15 | + |
| 16 | + |
| 17 | + // catch all Throwables in noNewData() and onRunError() |
| 18 | + @Test |
| 19 | + public void throwable() throws Exception { |
| 20 | + |
| 21 | + class ExceptionListener implements SerialInputOutputManager.Listener { |
| 22 | + public Exception e; |
| 23 | + @Override public void onNewData(byte[] data) { throw new RuntimeException("exception1"); } |
| 24 | + @Override public void onRunError(Exception e) { this.e = e; throw new RuntimeException("exception2"); } |
| 25 | + } |
| 26 | + class ErrorListener implements SerialInputOutputManager.Listener { |
| 27 | + public Exception e; |
| 28 | + @Override public void onNewData(byte[] data) { throw new UnknownError("error1"); } |
| 29 | + @Override public void onRunError(Exception e) { this.e = e; throw new UnknownError("error2");} |
| 30 | + } |
| 31 | + |
| 32 | + UsbEndpoint readEndpoint = mock(UsbEndpoint.class); |
| 33 | + when(readEndpoint.getMaxPacketSize()).thenReturn(16); |
| 34 | + CommonUsbSerialPort port = mock(CommonUsbSerialPort.class); |
| 35 | + when(port.getReadEndpoint()).thenReturn(readEndpoint); |
| 36 | + when(port.read(new byte[16], 0)).thenReturn(1); |
| 37 | + SerialInputOutputManager manager = new SerialInputOutputManager(port); |
| 38 | + manager.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); |
| 39 | + |
| 40 | + ExceptionListener exceptionListener = new ExceptionListener(); |
| 41 | + manager.setListener(exceptionListener); |
| 42 | + manager.run(); |
| 43 | + assertEquals(RuntimeException.class, exceptionListener.e.getClass()); |
| 44 | + assertEquals("exception1", exceptionListener.e.getMessage()); |
| 45 | + |
| 46 | + ErrorListener errorListener = new ErrorListener(); |
| 47 | + manager.setListener(errorListener); |
| 48 | + manager.run(); |
| 49 | + assertEquals(Exception.class, errorListener.e.getClass()); |
| 50 | + assertEquals("java.lang.UnknownError: error1", errorListener.e.getMessage()); |
| 51 | + assertEquals(UnknownError.class, errorListener.e.getCause().getClass()); |
| 52 | + assertEquals("error1", errorListener.e.getCause().getMessage()); |
| 53 | + } |
| 54 | +} |
0 commit comments