How to test IllegalStateException for getResultList of JAP Query - spring

I was trying to write a test for "IllegalStateException for getResultList of JAP Query". I am using spring to handle the transaction. Can anybody help me to produce this exception?
Sample Code
#Test (expected = IllegalStateException.class)
public void shouldThroughIllegalStateException() throws Exception {
List<SomeEntity> someEntitys= someDao.getAlldata();
}
Regards
Rajib

I am using Springockito to resolve this problem. Easy to use mocking framework.

Related

Mockito MockedStatic when() "Cannot resolve method"

I am trying to use Mockito MockedStatic to mock a static method.
I am using mockito-core and mockito-inline version 3.6.0 with Spring Boot and maven.
I can't manage to make the mock work, I have a "Cannot resolve method post" on the Unirest::post that you can see in the code below:
#Test
public void test() {
try (MockedStatic<Unirest> mock = Mockito.mockStatic(Unirest.class)) {
mock.when(Unirest::post).thenReturn(new HttpRequestWithBody(HttpMethod.POST, "url"));
}
}
The Unirest class comes from the unirest-java package.
Did someone encounter this issue already and have a solution?
The method Unirest.post(String url) takes an argument and hence you can't refer to it using Unirest::post.
You can use the following:
#Test
void testRequest() {
try (MockedStatic<Unirest> mockedStatic = Mockito.mockStatic(Unirest.class)) {
mockedStatic.when(() -> Unirest.post(ArgumentMatchers.anyString())).thenReturn(...);
someService.doRequest();
}
}
But keep in mind that you have to mock now the whole Unirest usage and every method call on it as the mock returns null by default.
If you want to test your HTTP clients take a look at WireMock or the MockWebServer from OkHttp. This way you test your clients with real HTTP communication and can test also corner cases like slow responses or 5xx HTTP codes.

How to use ITestResult for extend reports in JUnit Maven in #after

I am trying to capture screenshots in my extent report by using JUnit Maven.
I am able to generate the reports but ITestResult is not working in JUnit Maven in #After. I would highly appreciate if somebody can help in the code replacement from TestNG to Junit. Please find attached my code.
#After public void tearDown(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE){
String temp = Utility.getScreenshot(driver);
logger.fail(result.getThrowable().getMessage(), MediaEntityBuilder.createScreenCaptureFromPath(temp).build());
}
I assume you are using JUnit 5.
You will have to implement your own test execution listener based on the interface TestExecutionListener.
The following method will be called after any test execution:
default void executionFinished​(TestIdentifier testIdentifier,
TestExecutionResult testExecutionResult){
if(testExecutionResult.getStatus() == TestExecutionResult.Status.FAILED){
// your code here
}
}

if the exceptions have been swallowed, how does the spring aop log the exceptions' messages?

Here is my example bellow
public void test() throws Exception {
try {
int i = 1/0;
System.out.println(i);
} catch (Exception e) {
//the exception have been swallowed.
}
}
and the problem is spring aop's AfterThrowing can't work for this. if i remove the try-catch block.it works well then. how can i solve this problem. thanks for any suggestions.
Although it's unclear from question what you intend to achieve but this is the intended behavior of #AfterThrowing advice.
From docs -
After throwing advice runs when a matched method execution exits by throwing an exception.
which means that the advice will be executed only if an exception is thrown from method. In your sample the the exception is consumed and method exits normally thus no advice execution occurs.

Handling exceptions in Spring MVC along with Rest API

I am using #ControllerAdvice annotation for defining exceptions at application level. Now the problem is I am having two #ControllerAdvice classes, one for REST and one for the normal web app. When I define #ExceptionHandler for Exception.class in both, only the first one is considered. How do I separate both? Or how can I catch an Exception and determine from where it has occured? Is there a way or else do I need to use controller-specific exception handlers?
I resolved this issue by creating a custom exceptions for my application and giving one exception handler method for each of them with #exception handler.
I also used aspects to make sure that every exception is converted to any of the custom exceptions.
#Aspect
#Component
public class ExceptionInterceptor {
#AfterThrowing(pointcut = "within(x.y.package..*)", throwing = "t")
public void toRuntimeException(Throwable t)
throws ApplicationException1, ApplicationException2,ApplicationException3 {
if (t instanceof ApplicationException1) {
throw (ApplicationException1) t;
} else if (t instanceof ApplicationException2) {
throw (ApplicationException2) t;
} else
throw (ApplicationException3) t;
}
}
These will transfer control to #controlleradvice.
I noticed this have been left for a month or so, so it might be old. But this article may help http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/.
The section 3.5 is probably what you are looking for, a custom Exception Resolver.

Spring, Aspect J, multiple AfterThrowing advice applied to the same pointcut

Is it possible to have two AfterThrows pieces of advice be applied to the same pointcut restricted by specific Exception type where one exception is a superclass of the other with, in the case of the subclass being captured, only one advice being executed?
I want to translate runtime exceptions (both custom and standard java ones) being chucked out of a service layer, where I do some specific translation in certain cases and then have a catch-all type piece of advice to translate anything truly unexpected:
#AfterThrowing(pointcut = "execution(* com.my.company.api.*(..))", throwing = "rnfex")
public void doTranslationAction(ResourceNotFoundException rnfex) {
// throw new WebApplicationException with Status.NOT_FOUND;
}
#AfterThrowing(pointcut = "execution(* com.my.company.api.*(..))", throwing = "aex")
public void doTranslationAction(AuthorisationException aex) {
// throw new WebApplicationException with Status.NOT_AUTHORISED;
}
#AfterThrowing(pointcut = "execution(* com.my.company.api.*(..))", throwing = "throwable")
public void doTranslationAction(Throwable throwable) {
// Log something here about this unexpected exception
// throw new WebApplicationException with Status.INTERNAL_SERVER_ERROR
}
I find that in this case, if I throw an exception which is explicitly catered for then the correct method is called, a translated exception is thrown, which is then captured by the broader 'Throwable' advice, then translated again into the catch-all INTERNAL_SERVER_ERROR WAE. This isn't unexpected, but just not quite what I was looking for.
To get around this I've got a single piece of advice which captures all Throwable types and then uses 'instanceof' to decide whether this is an expected custom runtime exception that I can translate into a specific WAE or not.
If I ever see 'instanceof' I'm sure I've done something to be ashamed of, but I'm not sure if there's a better way of solving this problemette without it?
I'm also against converting my expected custom exceptions to checked exceptions and then catching Runtime exception as the catch all, which could be one solution.
I wrote a similar aspect a while ago and I ended up using "instance of". I don't think there's a problem with that.
i am not pretty sure... but just wondering whether your last(third) advice can be written in the below fashion
execution( * com.my.company.api..*(..)) and !execution( * com.my.company.api.XyzAspect..*(..))
public void doTranslationAction(Throwable throwable) {
// Log something here about this unexpected exception
// throw new WebApplicationException with Status.INTERNAL_SERVER_ERROR
}
where XyzAspect.java is the #Aspect class where in you are writing these 3 advices.

Resources