如果我有一个SUT,它使用try/catch块处理异常,如下所示:
public static void methodToBeTested() {
...
try {
desktop.browse(new URI("www.google.com"));
} catch (IOException e) {
//Display message to user and log out entry in app logs
}
...
}问题是,我是否应该从单元测试中测试抛出IOException的条件?(被测试的方法在默认浏览器中启动一个URI )
如果是,既然我没有从这个方法抛出异常,那么当desktop.browse()抛出一个IOException时,我该如何单元测试这个条件呢?
有什么想法或建议吗?我正在使用JMock
谢谢!
发布于 2015-07-04 15:19:21
基本上,您要做的是模拟桌面,无论何时向它发送浏览消息(无论使用什么URI ),它都应该抛出一个IOException,而不是命中那个URI。
我很久以前就用过Jmock了。据我所知,JMock有一些限制,例如它不提供模拟静态方法的机制。我不确定在jmock世界中模拟你的浏览器类有多容易。
然而,使用jmockit来测试它几乎是微不足道的,它支持各种奇特的模拟机制(包括静态引用、单例等)。(我之所以提到jmockit,是因为无论您的浏览类是什么,jmockit都可以模拟它。)
下面是一个excerpt from an example from their website
package jmockit.tutorial.domain;
import org.apache.commons.mail.*;
import jmockit.tutorial.persistence.*;
import org.junit.*;
import mockit.*;
public final class MyBusinessService_ExpectationsAPI_Test
{
@Mocked(stubOutClassInitialization = true) final Database unused = null;
@Mocked SimpleEmail anyEmail;
@Test
public void doBusinessOperationXyz() throws Exception
{
final EntityX data = new EntityX(5, "abc", "abc@xpta.net");
final EntityX existingItem = new EntityX(1, "AX5", "someone@somewhere.com");
new Expectations() {{
(1) Database.find(withSubstring("select"), any);
result = existingItem; // automatically wrapped in a list of one item
}};
new MyBusinessService(data).doBusinessOperationXyz();
(2) new Verifications() {{ Database.persist(data); }};
(4) new Verifications() {{ email.send(); times = 1; }};
}
@Test(expected = EmailException.class)
public void doBusinessOperationXyzWithInvalidEmailAddress() throws Exception
{
new Expectations() {{
(3) email.addTo((String) withNotNull()); result = new EmailException();
}};
EntityX data = new EntityX(5, "abc", "someone@somewhere.com");
new MyBusinessService(data).doBusinessOperationXyz();
}
}上面是被测试的类,下面是专门测试上面代码的(3)部分的测试。我认为这和你正在尝试做的事情很相似。请帮我看一下。
@Test(expected = EmailException.class)
public void doBusinessOperationXyzWithInvalidEmailAddress() throws Exception
{
new MockUp<Email>() {
@Mock
(3) Email addTo(String email) throws EmailException
{
assertNotNull(email);
throw new EmailException();
}
};
new MyBusinessService(data).doBusinessOperationXyz();
}
}如果你想坚持使用jmock,那也没问题。但是,您需要给我们更多关于Desktop类和它的浏览方法的信息,以便我们可以考虑在jmock世界中可以做些什么。
https://stackoverflow.com/questions/31217880
复制相似问题