Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

JUNIT test for @RequestPart

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I want to write a test for following controller method, on executing method of the testclass I'm getting an error as required part formData is not present, I've tried finding a solution for testing an object having 'RequestPart' annotation but no luck, can someone please take a look and suggest a way to write JUNIT test for @RequestPart

[code]

@PostMapping("/user")
public ResponseEntity<UserDTO> createUser(@RequestPart(value = "files", required= false) MultipartFile[] files,
@RequestPart("formData") UserDTO userDTO) throws URISyntaxException {

userService.save(userDTO, files);

//....

}

Inside TestClass-

@BeforeEach
public void initTest()
{
user = createEntity(em);// inside this method I've set all the properties of userDTO and 'user' is a reference variable to User class
}

public void createUser() throws Exception {

UserDTO userDTO = userMapper.toDto(user);

mockMvc.
perform(post("/api/user")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isCreated());
}
 
Ranch Hand
Posts: 1871
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, in your test case, first create a private method:


Then in your @Test method, do this:
 
pragati dev
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for this but when I also added WebConfig class as below I'm getting following error can you please suggest something
[code]
@Configuration
@ComponentScan({ "com.web.rest" })
@EnableWebMvc

public class WebConfig extends WebMvcConfigurationSupport {

 @Bean
 public MultipartResolver multipartResolver() {
   CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
   return multipartResolver;
 }


}
[code]

Error creating bean with name 'multipartResolver' defined in class path resource [com/web/rest/WebConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.multipart.MultipartResolver]: Factory method 'multipartResolver' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory  
 
Himai Minh
Ranch Hand
Posts: 1871
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, you may find this Stackoverflow post helpful.
You may need to add commons-fileupload dependency:
https://stackoverflow.com/questions/5166898/java-lang-noclassdeffounderror-org-apache-commons-fileupload-fileitemfactory
 
pragati dev
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks your solution did help, I've added the dependency but now when I execute the test method I get following error and when I debugged it I got createDate as
"createdDate":{
     "epochSecond":1589718619,
     "nano":876000000
  }
and createDate is a field of User object which of type Instant, can you please suggest how to resolve it?


   

: Bad Request: JSON parse error: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value
at [Source: (ByteArrayInputStream); line: 1, column: 33] (through reference chain: com.fis.pta.service.dto.UserDTO["createdDate"])
 
Himai Minh
Ranch Hand
Posts: 1871
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Is your userDTO an object or a Json string?
One thing you can try is to create a json string that represents your userDTO object.
 
pragati dev
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
 UserDTO is an Object whose values are set under createEntity method which executes when I run createUser() -test method  and that UserDTO has createDate field which is of Instant type and it is not being set in createEntity method is gets updated automatically
 
pragati dev
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have converted my UserDTO into json string but it's property createDate is being converted as
"createdDate":{
    "epochSecond":1589718619,
    "nano":876000000
 }
this is causing error
: Bad Request: JSON parse error: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value
at [Source: (ByteArrayInputStream); line: 1, column: 33] (through reference chain: com.fis.pta.service.dto.UserDTO["createdDate"])
any suggestions please to resolve it?
 
Himai Minh
Ranch Hand
Posts: 1871
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does your userDTO in json look like this

?
I guess the date format does not match with what your code expects.
 
please buy my thing and then I'll have more money:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic