当调用MQTTClient构造函数时,我需要抛出MQTTException,如下面的代码所示。
public MqttClient createClient(String url, String clientId) throws ServiceSDKException {
if (!(url.isEmpty() || url == null || clientId.isEmpty() || clientId == null)) {
try {
client = new MqttClient(url, clientId);
} catch (MqttException e) {
throw new ServiceSDKException("MqttException occurred when creating a new client", e);
} catch (IllegalArgumentException e) {
throw new ServiceSDKException("Illegal arguments detected, could be malformed url", e);
}
} else {
throw new ServiceSDKException("URL and ClientID cannot be null or empty");
}
return client;
}
@Override
@PrepareForTest(MqttClient.class)
@Test(expected = ServiceSDKException.class)
public void should_throw_ServiceSDKException_when_MqttException_occurs_while_creating_the_client() throws Exception {
PowerMockito.whenNew(MqttClient.class).withArguments(Matchers.anyString(), Matchers.anyString()).thenThrow(new MqttException(Mockito.mock(Throwable.class)));
MqttClient client = clientMqtt.createClient("tcp://localhost:1883", "100");
}
我也在课堂上添加了以下内容。
@RunWith(PowerMockRunner.class)
但是我收到一个断言错误,说我的异常没有被抛出。我尝试调试,在创建客户端实例时,它没有像我预期的那样抛出MQTTException。我在这做错了什么?我该如何测试这条线?请指教。