How to test Exception handler with mockito without a real controller call (Spring)
I have a Controller
@RequestMapping(value = "something/{year}", method = RequestMethod.GET)
@ResponseBody
public MyObject get(@PathVariable("year") int year throws MyException {
return myService.get(year);
}
If the year is not correct, it's gonna throw an error and this error is caught by my ErrorInterceptor class
@ExceptionHandler(value = {MyException.class})
protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest request) {
System.out.println(ex.getMessage());
ResponseEntity<Object> res = handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
ResponseEntity<Object> response = getMyResponse((ServletWebRequest) request, res);
return response;
}
The method getMyResponse creates an object with customed error message (path, code error, etc.) My question is how can I test it with Mockito without making a real call of the controller. I've tested with MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice(myInterceptor).build() but it's always null (I don't want to make a real call).
I also tried adding Mockito.when and Mockity.verify to fake the call but I can't get retrieve the path and stuff...
1 answer
-
answered 2022-05-04 14:53
EricSchaefer
If you just want to know if the interceptor is returning the correct response, you could create a class which is extenting the interceptor and provides an public wrapper method for
handleMyException
. Then you instantiate that new class, call the wrapper and assert on the returned response.
do you know?
how many words do you know
See also questions close to this topic
-
best way to add a spring boot web application with JSPs to a docker container?
so i have a spring boot web application, it uses JSPs, and im supposed to put it in a container .
my question is what is the best way ? ive tried to copy the project and then run it there using a wmvn like so : dockerfile:FROM openjdk:8-jdk-alpine ADD . /input-webapp WORKDIR /input-webapp EXPOSE 8080:8080 ENTRYPOINT ./mvnw spring-boot:run
which works, but it takes a long time getting the dependencies and feels messy .
and ive tried to package it into a jar, and then copy the jar only, and run it : dockerfile:
FROM openjdk:8-jdk-alpine ADD target/input-webapp-0.0.1-SNAPSHOT.jar input-webapp-0.0.1-SNAPSHOT.jar EXPOSE 8080:8080 ENTRYPOINT ["java","-jar","input-webapp-0.0.1-SNAPSHOT.jar"]
but this way it cant see the JSPs, or at least i think this is the problem, as i get a 404.
so is there a better way ? can i copy the jsps plus the jar to make it work? thanks
-
build spring boot (mvnw) with docker can not use cache
Spring Boot Docker Experimental Features Docker 18.06 comes with some “experimental” features, including a way to cache build dependencies. To switch them on, you need a flag in the daemon (dockerd) and an environment variable when you run the client. With the experimental features, you get different output on the console, but you can see that a Maven build now only takes a few seconds instead of minutes, provided the cache is warm.
my dockerfile can not use cache.
dockerfile
# syntax=docker/dockerfile:experimental FROM openjdk:8-jdk-alpine as build WORKDIR /workspace/app COPY mvnw . COPY .mvn .mvn COPY pom.xml . COPY src src RUN --mount=type=cache,target=/root/.m2 ./mvnw install -DskipTests -s .mvn/wrapper/settings.xml RUN mkdir -p target/extracted && java -Djarmode=layertools -jar target/*.jar extract --destination target/extracted FROM openjdk:8-jre-alpine ENV TZ Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN addgroup -S spring && adduser -S spring -G spring USER spring:spring ARG EXTRACTED=/workspace/app/target/extracted ARG JAVA_OPTS="-Xmx100m -Xms100m" COPY --from=build ${EXTRACTED}/dependencies/ ./ COPY --from=build ${EXTRACTED}/spring-boot-loader/ ./ COPY --from=build ${EXTRACTED}/snapshot-dependencies/ ./ COPY --from=build ${EXTRACTED}/application/ ./ ENTRYPOINT ["sh", "-c","java ${JAVA_OPTS} org.springframework.boot.loader.JarLauncher"]
run shell
DOCKER_BUILDKIT=1 docker build -t org/spring-boot .
every time use many minutes
-
How can I delete a row by its SKU instead of its ID?
I try to delete the row using the sku of the product. I'm using spring boot and angular. I got an error when I added the sku on my button like this one
(click)="onDeleteProductBySku(deleteClick?.sku)"
it said that theProperty 'sku' does not exist on type '(product: Product) => void'.
. On my command prompt, I got this error. How can I solve this problem?Error: product/product.component.html:50:109 - error TS2339: Property 'sku' does not exist on type '(product: Product) => void'. 50 <button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button> product/product.component.ts:12:16 12 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component ProductComponent.
ProductsController.java --> This is working on the postman.
//Delete a product record using sku //http://localhost:8080/products/deletebysku?sku=12345678 @DeleteMapping("/products/deletebysku") @ResponseBody private void deleteProductBySku(@RequestParam String sku){ productsService.deleteProductBySku(sku); }
product.component.ts
public deleteProduct!: Product; public onDeleteProductBySku(sku: string): void { this.productServive.deleteProductBySku(sku).subscribe( (response: void) => { this.messageShow(); console.log(response); this.getAllProduct(); }, (error: HttpErrorResponse) => { this.errorMessage(error.message); } ); } public deleteClick(product: Product) { this.deleteProduct = product; console.log("delete by sku"); }
product.service.ts
public deleteProductBySku(sku: string): Observable<void> { return this.http.delete<void>(`${this.apiServerUrl}/products/deletebysku?sku=${sku}`); }
product.component.html
<button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button>
-
Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something"""
I've written tests for the given as below.
@patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
-
Kotlin Coroutines Unit Testing
Im trying to test this suspend function:
suspend fun <T> getResult(call: suspend () -> Response<T>): Resource<T> { val response = call() val body = response.body() val code = response.code() if (response.isSuccessful) { Log.d(Cybrid.instance.tag, "Data: ${response.code()} - ${response.body()}") return Resource.success(body!!, code) } else if (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) { Cybrid.instance.let { cybrid -> cybrid.listener.let { cybrid.invalidToken = true it?.onTokenExpired() } } Log.e(Cybrid.instance.tag, "Error - Something wrong with TOKEN : ${response.code()} ${response.message()}") return Resource.error(response.message(), code=response.code()) } else { Log.e(Cybrid.instance.tag, "Error - Other: ${response.code()} ${response.message()} :: ${response.raw()}") return Resource.error(message = response.message(), data= response.body(), code= response.code()) } }
With this Unit Test Case, all it cover except line 13 , I dont know how to cover the line!!!
@ExperimentalCoroutinesApi @Test fun get400ErrorServerTest() = runBlocking { Cybrid.instance.setBearer("Bearer") val pricesService = AppModule.getClient().createService(PricesApi::class.java) val result = getResult { pricesService.listPrices() } Assert.assertNotNull(result) Assert.assertEquals(result.code, 400) Assert.assertNull(result.data) }
The coverage report says:
Some idea to get coverage for line 13 ??? Thnanks
-
Unit testing with get request
I am trying to create a unit test for one of my api.
In the frontend, I send it this way...
params = { participants: JSON.stringify(participants), section: JSON.stringify(section), }; axios.get('/api/list', params)
while in the controller, it receives the params this way...
public function list(Request $request) { $participants = json_decode($request->participants); $section = json_decode($request->section); }
Now, I tried making a unit test out of this. by doing...
$params = [ 'participants' => ['id', 'name', 'rating'], 'section' => ['id', 'code'], ]; $this->get('/api/list'.http_build_query($params))->assertStatus(200) // $this->json('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->getJson('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->call('GET', '/api/list', $params)->assertStatus(200) // -> also tried this one
But none of them works, it always says
TypeError: json_decode(): Argument #1 ($json) must be of type string, array given
.So, the way I built the url and the params must be all wrong,
so my question here is that, what's the correct way of building the url so that it provides a correct url string format and the controller will json_decode the params?
-
How to throw exception when there is extra parameters in request body spring boot
In my last project, there was a requirement for throwing exceptions when the request body contains extra parameters.
If the request will be like
{ "test":"body", "name":"HR 1", "location":"Location" }
where test parameter is unnecessary and I've to return a response that should be like
{ "timestamp": "2022-05-07T00:13:59.144657", "status": "500", "error": "Internal Server Error", "message": "test : must not be provided", "path": "/api/departments/HR" }
I've shared the answer. How I handled it.
-
Common object in two objects java
I am implementing one api and I have the following request bodies for 2 different endpoints:
endpoint1:
{ "requests": [ { "id": "123" } ] }
endpoint2:
{ "requests": [ { "variable": "stack" } ] }
Is there a way to build a common object for these 2 in java spring application?
-
Is using @CrossOrigin the same as overriding addCorsMapping() in Spring?
In my controller I currently added the following annotation
@CrossOrigin
:@RestController @RequestMapping(value = "/dev/test") @CrossOrigin public class MyController { ... }
And also wondering the following implementation in WebConfig:
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { private String allowedRequest = "/**"; private String allowedOrigins = "*"; private String[] allowedMethods = {"GET", "POST", "DELETE", "OPTIONS"}; @Override public void addCorsMappings(final CorsRegistry registry) { registry.addMapping(allowedRequest).allowedOrigins(allowedOrigins) .allowedMethods(allowedMethods); } }
Are those two options provide the same result? And are there any difference from security standpoint (which one is more secure than the other)?
Thank you!
-
Controller Target Class does not exist?
Im trying to follow a larval tutorial and make a controller. This is what I have so far and it works for the guy in the video but mine says controller not found. I don't know what to do to fix it. Thank you!
web.php file:
Route::get('/', [PagesController::class, 'home']);
PagesController.php file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\PagesController; class PagesController extends Controller { public function home() { return view('welcome', [ 'foo' => 'bar' ]); } }
-
MVC PHP - A better way to simplify my linking
I am looking for a way to create a solution to simplify my linking. On a site I am creating there will be multiple places (for example 15) where there will be a link to e.g. a privacy policy, and therefore when the URL to the policy changes I don't want to edit 15 different files, just change the URL in one place. I came up with this solution:
class PrivacyPolicy extends \Core\Controller { const PrivacyPolicyUrl = 'privacy-policy'; public function indexAction() { View::render('Privacy-policy/index.php', []); } }
and when I want to link to the privacy policy I do it like this
<a href="<?=ROOT?><?=App\Controllers\PrivacyPolicy::PrivacyPolicyUrl?>">Privacy policy</a>
But i don't feel like it's it.
Note: I don't want to create a file with paths for each page, but define the URLs locally as shown above. Is there a better way to do this?
-
Laravel Store , corrupted or not all are saved on database
public function patient_aprrovedischarge(Request $request, $id) { //get patient details $patientDischarge = DischargedPatients::where('id', '=', $id)->first(); //find patient update to DISCHARGE pending $updatepatient = Patients::find($patientDischarge->patient_id); $updatepatient->user_currently_at = 'DISCHARGED'; // //update discharge details $dischargepatient = DischargedPatients::find($id); $dischargepatient->status = 'approved'; $dischargepatient->discharged_by = auth()->user()->id; $dischargepatient->discharged_date = date('Y-m-d H:i:s'); // //save remarks $dischargeRemarks = new Remarks(); $dischargeRemarks->remarks_detail = 'Discharged Aprroved'; $dischargeRemarks->remarks_from = auth()->user()->id; $dischargeRemarks->user_from_type = 'MO'; $dischargeRemarks->patient_id = $patientDischarge->patient_id; $updatepatient->save(); $dischargepatient->save(); $dischargeRemarks->save(); return redirect('/medical/discharged')->with('success', 'Patient is now discharged!'); }
sorry , im not good with stack overflow, my problem is that not all of these 3 saves are on the database. its already uploaded on the hosting, maybe anyone can explain why, i think it has problem with the internet since sometimes it disconnects
-
How can i test this void method with junit?
I'm new in testing, and i have to test this especific void method with Junit, any thoughts? thanks!
public void createExcel(TarifaSurchargeResponse tarifaResponse, int rowCount, HSSFSheet sheet) { for (TarifaSurcharge tarifa : tarifaResponse.getTarifaSurcharge()) { if (Validator.isNotNull(tarifa)) { Row row = sheet.createRow(++rowCount); int columnCount = 0; Cell _cell = row.createCell(columnCount); _cell.setCellValue(TarifasSurchargeLocalUtil.reformatDate(tarifa.getFechaVenta())); _cell = row.createCell(++columnCount); _cell.setCellValue(tarifa.getCodigoComercio()); _cell = row.createCell(++columnCount); _cell.setCellValue(tarifa.getMontoVenta()); _cell = row.createCell(++columnCount); _cell.setCellValue("-"); } } }
-
NullPointerException when MockMvc performed in unit test
I'm trying to write a Java unit test but not sure where I'm going wrong. Likely a lack of understanding.
This is my test so far:
@Test public void getURL() throws Exception { when(restTemplate.exchange( anyString(), eq(HttpMethod.GET), httpEntityCapture.capture(), ArgumentMatchers.<ParameterizedTypeReference<List<MyAP>>>any(), urlParamCapture.capture())).thenReturn(new ResponseEntity<>(myAPs, HttpStatus.OK)); when(restTemplate.exchange( anyString(), eq(HttpMethod.GET), httpEntity2Capture.capture(), eq(ReissueCert.class), urlParam2Capture.capture())) .thenReturn(new ResponseEntity<>(reissueCert, HttpStatus.OK)); MvcResult result = mockMvc.perform(get(Endpoints.FWD_URL, "123") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .header("iv-user", email)) .andExpect(status() .isOk()) .andReturn(); assertEquals("Correct email sent", email, urlParamCapture.getValue()); assertEquals("Correct dob", "07-09-1981", urlParam2Capture.getValue()); assertEquals("Correct policy number", "123", urlParam3Capture.getValue()); }
When I run this I get a
NullPointerException
. The exception is from this line in my code:ReissueURL reissue = docHelper.getURL(accountService.getAccountDetails(req.getHeader(Constants.IVUSER)).getId().toString(), accountService.getAccountDetails(req.getHeader(Constants.IVUSER)).getDob(), policy);
I think the problem is that no value ever exists for
req.getHeader(Constants.IVUSER)).getDob()
in my test. I'm not certain though and I'm not sure what to do next.My debugger also shows this:
Cannot find local variable 'urlParam2Capture'
Also, FYI a get on
Endpoints.FWD
should return something like this:{ "reissueURL": "https://hostname/product/logon.htm/product/reissue.htm?clientId=4609&dob=01-01-1980&policyNumber=123" }
Here's the full stack trace:
14:13:15.005 INFO [service.name:myapi,,,] [main] INFO o.s.s.c.ThreadPoolTaskExecutor – Shutting down ExecutorService 'applicationTaskExecutor'
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:645) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72) at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at brave.servlet.TracingFilter.doFilter(TracingFilter.java:67) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at ie.avis.myapi.config.TivoliAuthenticationFilter.doFilter(TivoliAuthenticationFilter.java:46) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at ie.avis.myapi.config.TivoliAuthenticationFilter.doFilter(TivoliAuthenticationFilter.java:46) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.cloud.sleuth.instrument.web.ExceptionLoggingFilter.doFilter(ExceptionLoggingFilter.java:50) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at brave.servlet.TracingFilter.doFilter(TracingFilter.java:84) at org.springframework.cloud.sleuth.instrument.web.LazyTracingFilter.doFilter(TraceWebServletAutoConfiguration.java:138) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183) at ie.avis.myapi.controller.DocsControllerIT.getReissueCertURL(DocsControllerIT.java:283) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: java.lang.NullPointerException at ie.avis.myapi.service.account.AccountServiceReal.getAccountDetails(AccountServiceReal.java:72) at ie.avis.myapi.service.account.AccountServiceReal$$FastClassBySpringCGLIB$$6c77a5a0.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:687) at ie.avis.myapi.service.account.AccountServiceReal$$EnhancerBySpringCGLIB$$bc8047e0.getAccountDetails() at ie.avis.myapi.controller.DocsController.getReissueCertURL(DocsController.java:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ... 96 more
My
NullPointerException
comes from thegetAccountDetails
method:public AccountDetails getAccountDetails(String username) { LOG.debug("getAccountDetails triggered"); HttpHeaders headers = createHeaders(); headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); HttpEntity<String> request = new HttpEntity<>(headers); ResponseEntity<AccountDetails> response = restTemplate.exchange(accountAPIEndpoint + Constants.GET_ACCOUNT, HttpMethod.GET, request, AccountDetails.class, username); if (response.getStatusCode().is2xxSuccessful()) { LOG.debug("Request successful. Returning AccountDetails."); return response.getBody(); } else { return null; } }
I guess I need to mock an
AccountDetails
object for this. Is that correct and if so, how do I do that? -
type 'Null' is not a subtype of type 'Future<List<Account>>' - Bloc Test
I am trying to test a bloc which calls a function with two parameters. If I am removing the parameters and calling the below bloc test, it will pass, otherwise it will fail.
blocTest<AccountsBloc, AccountsState>( 'Account Bloc Testing', setUp: () { when( () { return mockRepo.getAccounts1( accessToken: '', userAddress: '', ); }, ).thenAnswer((_) async => Future.value(accountsMock)); }, build: () => AccountsBloc(mockRepo), act: (AccountsBloc bloc) { final accessToken = SharedPreferencesMock.getUserPreferences().accessToken ?? ''; final user = SharedPreferencesMock.loggedInUser(); bloc.add(AccountsBlocLoaded(accessToken, user)); }, expect: () => [ isA<AccountsLoading>(), ],
);
This is the error I am getting
type 'Null' is not a subtype of type 'Future<List<Account>>'
Anyone has any idea whats wrong?
This is the real function. The repo is mocked in the above code.
Future<List<Account>> getAccounts1({ required String userAddress, required String accessToken, }) async { return accountsMock; }
Bloc code looks like this
Future<void> _accountsInit( AccountsBlocLoaded event, Emitter<AccountsState> emit, ) async { emit(AccountsLoading()); await _opsRepository.getAccounts1( accessToken: event.accessToken, userAddress: event.user.userAddress, );
Thanks.