【发布时间】:2015-03-18 18:17:47
【问题描述】:
我想创建一个测试用例来测试我调用服务时授权是否有效。
我模拟我的服务,它将创建一个新的人。在将 Person 持久保存在数据库中之前,该服务将执行一些逻辑和验证。验证之一是验证用户是否被授权这样做。如果不是授权,就会抛出异常。
验证在我的服务中完成。
问题是我不知道如何创建测试用例来重现该用例。我不知道如何模拟被模拟对象抛出的异常。
@RunWith(JMockit.class)
public class RESTServiceTest {
@Mocked
private IMessageService messageService;
private final IRESTService service = new RESTService();
@Test
public void testNew() throws Exception {
final Person person = new Person();
new NonStrictExpectations() {
{
Deencapsulation.setField(service, messageUtil);
Deencapsulation.setField(service, messageService);
// will call securityUtil.isValid(authorization); //that will throw a InvalidAuthorizationException
messageService.createPerson(person, authorization);
//messageService will catch the InvalidAuthorizationException and throw an exception : NOTAuthorizedException();
}
};
Person createdPerson = service.newPerson(person, "INVALID AUTHORIZATION");
这里是功能的示例:
public class RESTService implements IRESTService {
public Person newPerson(Person person, String authorization){
...
messageService.createPerson(person, authorization);
...
return person;
}
}
public class MessageService implements IMessageService {
public void createPerson(Person person, String authorization){
try {
... // private methods
securityUtil.isValid(authorization); // will throw InvalidAuthorizationException is invalid
...
create(person);
...
} catch(InvalidAuthorizationException e){
log.error(e);
throw new NOTAuthorizedException(e);
}
}
}
【问题讨论】: