I have created two test cases out that one was working fine. While testing for the "/account/accountNumber" endpoint, I got an error.
Below is my controller test cases:
package com. bank;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.coyote.Response;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.bank.model.Account;
import com.bank.model.Customer;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CapstoneBankProjectApplicationTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
ObjectMapper objectMapper=new ObjectMapper();
@Before
public void setUp() {
mockMvc=MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testcreateAccount() throws Exception {
Customer customer=new Customer();
customer.setCustomerId(1);
customer.setCustomerName("Manasa");
Account account=new Account();
account.setAccountNumber(456);
account.setAccountType("savings");
account.setBalance(2000.0);
account.setCustomer(customer);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
String JsonRequest=objectMapper.writeValueAsString(account);
MvcResult result=mockMvc.perform(post("/account").content(JsonRequest).contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isCreated()).andReturn();
String resultContext=result.getResponse().getContentAsString();
Response response=objectMapper.readValue(resultContext,Response.class);
Assert.assertTrue(response.getStatus()==200);
}
@Test
public void testgetAccountById() throws Exception{
MvcResult result = mockMvc.perform(get("/account/accountNumber").contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk()).andReturn();
String resultContext = result.getResponse().getContentAsString();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Response response = objectMapper.readValue(resultContext, Response.class);
Assert.assertTrue(response.getStatus() ==200);
}
}
is there anything wrong?
console result:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /account/accountNumber
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8"]
Body = null
Session Attrs = {}
Handler:
Type = com.bank.controller.AccountController
Method = com.bank.controller.AccountController#getAccountById(int)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
2022-03-21 13:20:40.698 INFO 8696 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-03-21 13:20:40.698 INFO 8696 --- [ionShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2022-03-21 13:20:40.701 WARN 8696 --- [ionShutdownHook] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 90121, SQLState: 90121
2022-03-21 13:20:40.701 ERROR 8696 --- [ionShutdownHook] o.h.engine.jdbc.spi.SqlExceptionHelper : Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200]
2022-03-21 13:20:40.704 WARN 8696 --- [ionShutdownHook] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 90121, SQLState: 90121
2022-03-21 13:20:40.705 ERROR 8696 --- [ionShutdownHook] o.h.engine.jdbc.spi.SqlExceptionHelper : Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200]
2022-03-21 13:20:40.705 WARN 8696 --- [ionShutdownHook] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'entityManagerFactory': org.hibernate.exception.JDBCConnectionException: Unable to release JDBC Connection used for DDL execution
2022-03-21 13:20:40.706 INFO 8696 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-03-21 13:20:40.711 INFO 8696 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
this is Junit console result:
java.lang.AssertionError: Status expected:<200> but was:<400>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
at com.bank.CapstoneBankProjectApplicationTests.testgetAccountById(CapstoneBankProjectApplicationTests.java:78)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
this is my controller:
package com.bank.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bank.model.Account;
import com.bank.service.AccountService;
import com.bank.Exception.ResourceNotFoundException;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
AccountService accountService;
@PostMapping
public ResponseEntity<?> createAccount(@RequestBody Account account) throws ResourceNotFoundException{
Account acc=accountService.accountCreate(account);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.CREATED);
}else {
throw new ResourceNotFoundException("Account is not Created!!");
}
}
@GetMapping("/aclist")
public ResponseEntity<?> accountList() throws ResourceNotFoundException{
List<Account> accountList=accountService.allAccounts();
if(!(accountList.isEmpty())) {
return new ResponseEntity<>(accountList,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("accounts not found");
}
}
@GetMapping("/byType/{accountType}")
public ResponseEntity<?> byAccountType(@PathVariable String accountType) throws ResourceNotFoundException{
List<Account> account =accountService.accountByType(accountType);
if(account.isEmpty()) {
throw new ResourceNotFoundException(accountType "" "Type of account does not exist!!");
}else {
return new ResponseEntity<>(account,HttpStatus.OK);
}
}
@GetMapping("/{accountNumber}")
public ResponseEntity<?> getAccountById(@PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
Account acc=accountService.findAccountById(accountNumber);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("account [accountNumber=" accountNumber "] can't be found");
}
}
@PutMapping("/{from}/{to}/{amount}")
public ResponseEntity<?> transferFunds(@PathVariable("from") int from,@PathVariable("to") int to,@PathVariable("amount") double amount) throws ResourceNotFoundException{
return accountService.transferFunds(from, to, amount);
}
@DeleteMapping("/{accountNumber}")
public ResponseEntity<?> deleteAccById(@PathVariable ("accountNumber") int accountNumber) throws ResourceNotFoundException{
String x=accountService.deleteById(accountNumber);
if(x.equalsIgnoreCase("deleted")){
return new ResponseEntity<>("deleted successfully",HttpStatus.OK);
}else {
throw new ResourceNotFoundException("Account [accountNumber=" accountNumber "] can't be found");
}
}
@GetMapping("/balance/{accountNumber}")
public ResponseEntity<?> getBalanceById(@PathVariable ("accountNumber") int accountNumber) throws ResourceNotFoundException{
String balance=accountService.getBalanceById(accountNumber);
if(balance.equalsIgnoreCase("Invalid accountNumber")) {
throw new ResourceNotFoundException("Account [accountNumber=" accountNumber "] can't be found");
}else {
return new ResponseEntity<>(balance,HttpStatus.OK);
}
}
@DeleteMapping("/deleteAll")
public ResponseEntity<?> deleteAllAccounts(){
return new ResponseEntity<>(accountService.deleteAllAccounts(),HttpStatus.OK);
}
@PutMapping("/update/{accountNumber}")
public ResponseEntity<?> UpdateAccount(@PathVariable ("accountNumber") int accountNumber,@RequestBody Account account) throws ResourceNotFoundException{
Account acc=accountService.updateAccount(accountNumber, account);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("invalid accountNumber and account");
}
}
@PutMapping("/deposite/{amount}/{accountNumber}")
public ResponseEntity<?> deposite(@PathVariable("amount") double amount,@PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
return accountService.deposite(amount,accountNumber);
}
@PutMapping("/withdraw/{amount}/{accountNumber}")
public ResponseEntity<?> withDraw(@PathVariable("amount") double amount,@PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
return accountService.withdraw(amount,accountNumber);
}
}
for me Assert.asserTrue(response.isStatus()==Boolean.True)
was not supporting so I used Assert.assertTrue(response.getStatus() ==200)
CodePudding user response:
The HTTP 400 response indicates a bad request. Your HTTP GET endpoint expects an int
while you're sending a String
as the path variable.
So accountNumber
must be a real number like 123
:
MvcResult result = mockMvc
.perform(get("/account/123")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andReturn();