Unable to Mock the Database call handled by Spring JPA framework while writing test Case for Controller Class - spring-mvc

Spring MVC converts the id from path to corresponding object by making call to JpaRepository's findById method. For example see getVersionTree() method.
public class Controller {
#NonNull
private final MyService service;
#NonNull
private final MyAssembler assembler;
#GetMapping(path = VERSION_TREE_MAPPING, produces = MediaTypes.HAL_JSON_UTF8_VALUE)
public HttpEntity<?> getVersionTree(#PathVariable("id") MappingDocument mappingDocument, Pageable pageable, PagedResourcesAssembler<VersionNode> pagedResourcesAssembler) {
Page<VersionNode> versionNodes = service.getVersionTreeFor(mappingDocument, pageable);
return new ResponseEntity<>(pagedResources, HttpStatus.OK);
}
While testing, SpringMVC throws " Failed to convert value of type 'java.lang.String' to required type 'com.rbc.dna.dtl.mappingdocument.MappingDocument'". I am mocking jpaRepository.findById() method. Test Code is as follows:
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private MyRepository repository;
#Mock
MyController controller;
#MockBean
private MyServiceImpl serviceImpl;
#Test
public void testMethod() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(SecurityMockMvcConfigurers.springSecurity()).build();
MappingDocument mappingDocumentl=MappingDocument.builder().id(17L).build();
Mockito.when(repository.findById(17L)).thenReturn(Optional.of(mappingDocumentl));
Mockito.when(serviceImpl.getVersionTreeFor(mappingDocument,pageable)).thenReturn(pagedResponse);
mockMvc.perform(MockMvcRequestBuilders.get("/abc/17/def").param("page","0").param("size","20").contentType(MediaTypes.HAL_JSON_UTF8_VALUE)
.with(authentication(getOauthTestAuthentication()))
.sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
.andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}

Your rest Controller take #PathVariable("id") MappingDocument mappingDocument as variable in your path, but in mockMvc.perform you are passing a simple String/Number or something that doesn't bind with MappingDocument.
Try to replace
public HttpEntity<?> getVersionTree(#PathVariable("id") MappingDocument mappingDocument...
with
public HttpEntity<?> getVersionTree(#PathVariable("id") Long idMappingDocument, ...
If you want to keep your object in #PathVariable you need to change
#GetMapping(path = VERSION_TREE_MAPPING)
To parse an object as PathVariable you need to have path that represent property of your object.
For example if you have
class Person {
String name;
String address;
//getters and setters
}
and you need to define a controller as follow:
#GetMapping(path = "/person/{name}/{address}", produces = MediaTypes.HAL_JSON_UTF8_VALUE)
public HttpEntity<?> getVersionTree(Person person) {
Where {name} and {address} must bind Person properties

Related

No mapping found for HTTP request with URI [/api/transactions] in DispatcherServlet with name ''

I thought this is a standard configuration. But I get a 404 back. Where else should I configure Spring Boot ?
#RestController
#RequestMapping("/api")
public class TransactionStatisticsController {
public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);
#RequestMapping(value = "/transactions",
method = RequestMethod.POST)
public ResponseEntity sendTransaction(#RequestBody Transaction request) {
logger.info( request.toString());
return new ResponseEntity(HttpStatus.OK);
}
}
This is my test.
#JsonTest
#SpringBootTest(classes = Application.class)
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class TransactionStatisticsRestTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private JacksonTester<Transaction> json;
private static Transaction transaction;
#BeforeClass
public static void createTransaction(){
BigDecimal amount = new BigDecimal(12.3343);
transaction = new Transaction(amount.toString(),
"2010-10-02T12:23:23Z");
}
#Test
public void getTransactionStatus() throws Exception {
final String transactionJson = json.write(transaction).getJson();
mockMvc
.perform(post("/api/transactions")
.content(transactionJson)
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsBytes(transaction);
}
}
Request being made is
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/transactions
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = {"amount":"12.3343000000000007077005648170597851276397705078125","timestamp":"2010-10-02T12:23:23Z[UTC]"}
Session Attrs = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Update : I added a component scan pointing to a base package. I don't see that error now. Please see the comments where there is an answer.
As in the comment section ,there was only requirement was to bind a component scan base package location .
#Component scan -->Configures component scanning directives for use with #Configuration classes. Provides support parallel with Spring XML's element.
Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Please share your project folder architecture. It might be possible that your controller package is out of the main class package. That's why it is showing 404.
This code :
#RestController
#RequestMapping("/api")
public class TransactionStatisticsController {
public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);
#RequestMapping(value = "/transactions",
method = RequestMethod.POST)
public ResponseEntity sendTransaction(#RequestBody Transaction request) {
logger.info( request.toString());
return new ResponseEntity(HttpStatus.OK);
}
}
This should be into your main package where
#SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
this main class resides.
I hope, this will help.
Seems using #JsonTest does not even allow to load Application Context, results mapping is not loaded and its throw 404 so #JsonTest is not a replacement for #SpringBootTest, it is a way to easily test json serialization/de-serialization.
As per documentation:
you can use the #JsonTest annotation. #JsonTest auto-configures the
available supported JSON mapper, which can be one of the following
libraries:
Jackson ObjectMapper, any #JsonComponent beans and any Jackson Modules
Gson
Jsonb
If by using Gson and removing #JsonTest your test run fine..(add Gson Dependency in pom)
#SpringBootTest
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class DemoKj01ApplicationTests {
#Autowired
private MockMvc mockMvc;
private static Transaction transaction;
#BeforeClass
public static void createTransaction(){
BigDecimal amount = new BigDecimal(12.3343);
transaction = new Transaction(amount.toString(),
"2010-10-02T12:23:23Z");
}
#Test
public void getTransactionStatus() throws Exception {
//final String transactionJson = json.write(transaction).getJson();
Gson gson = new Gson();
String jsonRequest = gson.toJson(transaction);
mockMvc
.perform(post("/api/transactions")
.content(jsonRequest)
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
It is beacause of the trailing slas in #RequestMapping(value = "/transactions/", method = RequestMethod.POST)
Remove it and it will be ok : value = "/transactions/" => value = "/transactions"

how to get the values from properties file in the test cases

I am getting null while reading the values from .properties file when i am executing the test case. here while debugging the test case i am able to see the values which are loaded from properties file when the curser is there in the test class but when the curser enters into the actual class in that class i am getting the same values as null. And my code is as follows
Thanks in advance
#RestController
#PropertySource("classpath:/com/example/prop.properties")
public class ReadProp {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#RequestMapping(value="/")
public void getDetails(){
System.out.println(name);
System.out.println(rollNo);
}
}
and the test case is as follows
#RunWith(SpringRunner.class)
#SpringBootTest
#PropertySource("classpath:/com/example/prop.properties")
public class ReadPropTest {
private ReadProp readProp = new ReadProp();
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#Test
public void readValues() {
System.out.println(name);
System.out.println(rollNo);
readProp.getDetails();
}
}
Instead of creating a new object using new ReadProp(). You should Autowire it.
#Autowired
ReadProp readProp;
in your test class. If you create an object using new, you don't get the bean which spring created with all the value assigned using #Value.
Try something like this :
#PropertySource("classpath:prop.properties")// your error
public class ReadPropTest {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
}

mvc controller test with session attribute

I'm trying to test a method with this signature:
#Autowired
HttpSession http_Session;
#RequestMapping(method=RequestMethod.GET, value="/search/findByName")
public #ResponseBody List<Map> search(#RequestParam(value="name", required=true) String name){
Integer user_id = http_Session.getAttribute("userinfo");
}
userinfo is a class which contains informations about the user and set in session scope when the user logged in.but when I try the test :
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = {
"classpath:/META-INF/applicationContext.xml"})
public class userControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
#Test
public void userTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/search/findByName").param("name", "bob"))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk());
}
The problem is the userinfo class attribute is set in another method so when i try to access it in this method i got a NullPointerException , and with Autowiring the httpSession i got a new Session for each method i have to test.
What should i do with the session attribute, my method doesn't accept a session parameter , and for each test it create a WebApplicationContext with a new session.
Try this :
HashMap<String, Object> sessionattr = new HashMap<String, Object>();
sessionattr.put("userinfo", "XXXXXXXX");
mockMvc.perform(MockMvcRequestBuilders.get("/search/findByName").sessionAttrs(sessionattr).param("name", "bob"))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk());
You could also share a session across different requests:
import static org.springframework.test.web.servlet.setup.SharedHttpSessionConfigurer.sharedHttpSession;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.webApplicationContext)
.apply(sharedHttpSession()) // use this session across requests
.build();
}
note: this session will be shared among requests performed against the same MockMvc instance only.

How to pass parameter to controller to get the correct object in spring mvc

I define an object like
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
public String getTotalMileage () {
return totalMileage;
}
public void setTotalMileage (String totalMileage) {
this.totalMileage = totalMileage;
}
public String getMileageTime () {
return mileageTime;
}
public void setMileageTime (String mileageTime) {
this.mileageTime = mileageTime;
}
}
}
and my controller is like:
#RequestMapping(value="saveDriveLog",method = RequestMethod.GET)
public #ResponseBody ResultBean saveDriveLog(DrivelogBean drivelogBean){
driveLogService.addDriveLog (drivelogBean);
ResultBean resultBean = new ResultBean();
resultBean.setRet (1);
resultBean.setDescripion (UsConstants.DRIVELOG_SAVE);
return resultBean;
}
I want request parameters convert to drivelogBean
and my url is like that:
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?backInfoIdentify=2&totalMileageIntd["driverNum%22]=1&totalMileageIntd["driveCode"]=2
but the page prompt
HTTP ERROR: 404 Problem accessing //manage/drivelog/saveDriveLog/error. Reason:Not Found
and i change the url like :
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?commendWord=2&totalMileageIntd.driverNum=1&totalMileageIntd.driveCode=2
but the drivelogBean parameter, the property driverNum of totalMileageIntd and the property driveCode of totalMileageIntd is null.
So how can I set the correct url pass parameter to the drivelogBean?
I don't know if binding inner static class works in spring.
Your parametter must match a setter
commendWord=2 => you must have setCommendWord on the class DrivelogBean
totalMileageIntd.driverNum=1 => you must have a setDriverNum() on and a getTotalMileageIntd
The class should look like this (I skipped getter and setter to save space but they must exists)
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
private TotalMileageIntd totalMileageIntd ;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
}
}
In this case all the parametter you can use are :
backInfoIdentify=XXX
driVehNum=XXX
totalMileageIntd.totalMileage=XXX
totalMileageIntd.mileageTime=XXX
nothing else

Spring MVC - PropertyEditor not called during ModelAttribute type conversion

Using Spring 3.2.3, I'm trying to implement a simple CRUD controller that handles REST-ful URLs. It relies on a PropertyEditor to convert a path variable to a BusinessService entity by loading it from an application service. Code is as follows:
#Controller
public class BusinessServiceController {
#Autowired
private BusinessServiceService businessSvcService;
public BusinessServiceController() {
}
#InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(BusinessService.class, new BusinessServicePropertyEditor(businessSvcService));
}
#RequestMapping(value = "/ui/account/business-services/{businessSvc}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView update(#ModelAttribute("businessSvc") #Valid final BusinessService businessSvc, final BindingResult result,
final RedirectAttributes redirectAttribs) throws UnknownBusinessServiceException {
ModelAndView mav;
if (result.hasErrors()) {
mav = new ModelAndView("/business-service/edit");
}
else {
businessSvcService.updateBusinessService(XSecurity.principal().getId(), businessSvc);
mav = new ModelAndView("redirect:/ui/account/business-services");
redirectAttribs.addFlashAttribute("message", Message.info("businessService.updated", businessSvc.getTitle()));
}
return mav;
}
}
public class BusinessServicePropertyEditor extends PropertyEditorSupport {
private final BusinessServiceService businessSvcService;
public BusinessServicePropertyEditor(final BusinessServiceService businessSvcService) {
this.businessSvcService = businessSvcService;
}
#Override
public String getAsText() {
final BusinessService svc = (BusinessService) getValue();
return Long.toString(svc.getId());
}
#Override
public void setAsText(final String text) {
final BusinessService svc = businessSvcService.getBusinessService(Long.parseLong(text));
setValue(svc);
}
}
According to SPR-7608, starting from Spring 3.2, #ModelAttribute method argument resolution checks if a path variable by the same name exists (it does here), in which case it tries to convert that path variable's value to the target parameter type through registered Converters and PropertyEditors. This is not what I'm experiencing. When I inspect what ServletModelAttributeMethodProcessor does, it clearly uses the request DataBinder's ConversionService to perform type conversion, which does not consider registered PropertyEditors, and hence BusinessServicePropertyEditor#setAsText is never called.
Is this a configuration problem or an actual bug?
Thanks for your help!
Spring's ConversionService and Converters are replacement for standard Java Beans PropertyEditors.
You need to implement Converter instead of PropertyEditor if this feature is based purely on conversion service.
To register your custom converters in WebDataBinder you might use ConfigurableWebBindingInitializer or #InitBinder method.

Resources