Here is my Controller:
@RestController
public class LoanController {
@Autowired
private LoanService loanService;
@GetMapping("/loans/{id}")
public Loan getLoan(@PathVariable Long id) {
return loanService.getLoan(id);
}
@PostMapping("/loans")
public ResponseEntity <String> addLoan(@RequestBody Loan loan) {
System.out.println(" Test 2 >> " + loanService.isLoanProcessed(loan));
if(loanService.isLoanProcessed(loan)) {
return ResponseEntity.status(HttpStatus.CREATED).build(); //return http 201 return code
}
return ResponseEntity.status(HttpStatus.CONFLICT).build(); // return http 409 return code
}
}
Service :
@Service
public class LoanService {
@Autowired
private LoanRepository loanRepo;
public boolean isLoanProcessed(Loan loan) {
// Validate the Loan
if(isValid(loan)) {
// Get the Loan Fee
Double loanFees = getLoanFees(loan.getLoanType().trim());
// Get the total Loan Interest
Double totLoanInterest = calcLoanTotalInterest(loan.getLoanAmt(),loan.getRate(),loan.getLoanTerm());
// Get the APR
Double apr = getAPR(totLoanInterest,loanFees,loan.getLoanAmt(),loan.getLoanTerm());
// Set calculate APR to Loan model
loan.setApr(apr);
// Add the loan to db
this.addLoan(loan);
return true;
} else {
// If the Loan is not valid throw custom exception
// Still need to be implemented
return false;
}
}
Here is the TestClass :
@SpringBootTest
@AutoConfigureMockMvc
public class LoanControllerIntegrationTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private LoanService mockLoanService;
private AutoCloseable closeable;
@InjectMocks
LoanController loanController;
private Loan loan;
private SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
@BeforeEach
public void init() throws Exception {
closeable = MockitoAnnotations.openMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(loanController).build();
}
@Test
@DisplayName("POST /loans")
final void addLoanIdTest() throws Exception {
loan.setApr(Double.valueOf(5.15));
loan.setLoanStatus("A");
when(mockLoanService.isLoanProcessed(loan)).thenReturn(true);
System.out.println(" Test 1 >> " + mockLoanService.isLoanProcessed(loan)); // printing true
mockMvc.perform(post("/loans")
.contentType(MediaType.APPLICATION_JSON)
.content(convertObjToJsonString(loan)))
.andExpect(status().isOk());
}
Here is my question :
In the test, mocking happening correctly when I print on mockLoanService.isLoanProcessed(loan) value is correct which is true, But in Controller, post method modified mocking data is not picking, when I print showing as false, condition check on controller if(loanService.isLoanProcessed(loan)) not happening using mocking data. Please provide your input where I am making mistake.
