I want to create a testcase to test it the authorization is valid or not when I call the service.
I Mock my service that will create a new Person. The service will do some logic and validation before persisting the Person in the database. One of the validation, is to validate if the user is authorized to do that. If it's not authorization, there will be a exception that will be thrown.
That validation is done in my service.
The problem, is that I don't know how to create the test case to reproduce that usecase. I don't know how to mock an exception thrown by a mocked object.
@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");
Here an example how functionality look like :
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);
}
}
}