I'm building rest-assured test for rest controller.
Rest-assured test:
#Test
fun saveFileReturnsFileKeyAndStatusCreated() {
given()
.multiPart("file", File("d:/2.txt"))
.multiPart("fileDescription", "...file description here...")
.multiPart("fileExtension", ".txt")
.`when`()
.post("/file")
.then()
.statusCode(HttpStatus.CREATED.value())
.body(notNullValue<String>(String::class.java))
}
Rest controller method:
#RestController
#RequestMapping(produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE))
class ClientActionsController(private var clientActionsService: ClientActionsService) {
#PostMapping(value = "/file", consumes = arrayOf(MediaType.MULTIPART_FORM_DATA_VALUE))
fun saveFile(request: HttpServletRequest): ResponseEntity<String> {
println(request.getPart("fileDescription"))
println(request.getPart("fileExtension"))
println(request.getPart("file"))
return ResponseEntity(clientActionsService.saveFile(request), HttpStatus.CREATED)
}
}
Real code works fine, but when I start the test all the parts in request are null.
What might be the cause for not receiving rest-assured's multiparts in rest controller's HttpServletRequest?
Spring Boot 1.5.8, rest-assured 3.0.5
The reason your file is null, because in your test configuration class, you need to have #bean for MultipartFileResolver.
Something like this:
#Bean
public MultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
Related
/I'm trying to use a Feign-client to communicate another rest service
which will return status code 204 with no body/
public interface DepartmentApi {
#RequestLine("GET /department/nocontent") /*Department Client*/
#Headers("Content-Type: application/json")
ResponseEntity<Void> getDepartment();
}
#Component
public class ClientApiFactory {
#Bean
#RequestScope
public DepartmentApi getDepartmentApi() { /*Bean for Department client */
return HystrixFeign.builder()
.logLevel(Logger.Level.BASIC)
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.target(DepartmentApi.class, "http://localhost:8080");
}
}
#GetMapping(value = "/nocontent") /*Department Service which is running on 8080*/
ResponseEntity<Void> noContent() {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
I would like to retrieve the status code from the response for the void methods, but with a void method there is no way to get to the status ,it's returns[ReponseEntity] null.
Is there a way to retrieve the HTTP status code from a Feign method for a resource that returns no body? They all fail with a nullpointer exception because of the lack of response body.
In my Micronaut app I have a simple REST controller:
public class Response {
private String code;
public Response(String code) {
this.code = code;
}
}
#Controller("/api/test")
public class TestController {
#Post("/")
public Response index() {
return new Response("OK");
}
}
How can I tests this edpoint? I tried using
#MicronautTest
public class TestControllerTest {
#Inject
EmbeddedServer server;
#Inject
#Client("/")
HttpClient client;
#Test
void testResponse() {
String response = client.toBlocking()
.retrieve(HttpRequest.POST("/api/test/")); // FIXME `HttpRequest.POST` requires body
assertEquals("{\"code\": \"OK\"}", response);
}
but HttpRequest.POST requires an additional body argument to be specified. In my case there is no body to be sent. (In the real code it is a request to initialize a new object and thus it has to be POST).
Usually, when you implement a POST action, you expect that there is a body sent with the request. In your example, you don't accept any POST body, but you still need to pass anything in the unit test.
You can instantiate the HttpRequest object in the following way:
HttpRequest.POST("/api/test/", "");
You can't pass null, it has to be some non-null value (like an empty string.)
I am working spring boot, spring integration, gradle project. And I am using junit and Mockito for mocking my soap service. And Basically I have these three classes for my application.
Junit Class for mocking soap service.
#Before
public void setup() {
gw=Mockito.mock(ProjectGateway.class);
pc=new ProjectController();
pc.setGateWay(gw);
}
#Test
public void testGetProject() throws Exception {
GetAuthorizedWebSendTransferProjects mockRequest=new GetAuthorizedWebSendTransferProjects();
GetAuthorizedWebSendTransferProjectsResponse mockResponse=getMockResponse();
when(gw.getResponse(mockRequest)).thenReturn(mockResponse);
List<Project> projects=pc.getProject();
assertEquals(1,projects.size());
}`
and an interface which calls soap service.
`public interface ProjectGateway {
public GetAuthorizedWebSendTransferProjectsResponse getResponse(
GetAuthorizedWebSendTransferProjects request);
}'
and the method on which I need to do unit testing.
#RequestMapping(value = "/projects", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Project> getProject() {
GetAuthorizedWebSendTransferProjects request = new GetAuthorizedWebSendTransferProjects();
GetAuthorizedWebSendTransferProjectsResponse response = gw
.getResponse(request);
JAXBElement<ArrayOfProjectContainer> arr = response
.getGetAuthorizedWebSendTransferProjectsResult();
ArrayOfProjectContainer arr1 = arr.getValue();
List<ProjectContainer> arr2 = arr1.getProjectContainer();
List<Project> projects = getPopulatedProjectList(arr2);
return projects;
}
But I am getting an nullpointerexception in "List projects=pc.getProject();" of test method. Can anybody help me out in this issue. Thank you in advance.
The issue is that the instance of request that is expected by the mock does not match the instance that is actually passed. Therefore the condition doesn't match and the mock is returning null.
Use
when(mock.getResponse(
Mockito.isA(GetAuthorizedWebSendTransferProjects.class)))
.thenReturn(...)
I use this sample tutorial to create a simple Web API.
Then I downloaded the PCL version of RestSharp from here, compiled and tried to execute this test code:
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var client = new RestClient("http://localhost:18506/api/");
var request = new RestRequest("products", Method.GET);
client.ExecuteAsync<List<Product>>(request, response =>
{
foreach (var a in response.Data)
{
Console.WriteLine(a.Name);
}
});
}
public class Product
{
public string Name { get; set; }
}
}
Nothing is being written to the console and if I put a break point within the call back, it is not hit.
Any suggestions?
TIA.
You've triggered an asynchronous HTTP call and never seem to be waiting for it to complete. Try waiting or your unit test might finish much before the Web API is even hit by the request:
client.ExecuteAsync<List<Product>>(request, response =>
{
...
}).Result;
But in a unit test you probably don't need to be complicated your life with asynchronous HTTP calls. Just use a standard synchronous call and assert on the results received.
I'm successfully using Spring.net Rest on WP7 since this issue.
My REST service requires a specific content type. I tried to used another request interceptor but XElementHttpMessageConverter overrides the content type.
public MyClient(string baseAddress)
{
restTemplate = new RestTemplate(baseAddress);
//restTemplate.RequestInterceptors.Add(new NoCacheRequestInterceptor());
restTemplate.MessageConverters.Add(new XElementHttpMessageConverter());
}
public MyObject GetMyObject(int id)
{
XElement element = restTemplate.GetForObject<XElement>("path/{id}", id);
//..
return myObject;
}
// more methods
The best way here to do that is to configure your converter with the "SupportedMediaTypes" property :
public MyClient(string baseAddress)
{
restTemplate = new RestTemplate(baseAddress);
//restTemplate.RequestInterceptors.Add(new NoCacheRequestInterceptor());
XElementHttpMessageConverter linqXmlConverter = new XElementHttpMessageConverter ();
linqXmlConverter.SupportedMediaTypes = new MediaType[] { MediaType.Parse("type/subtype") };
restTemplate.MessageConverters.Add(linqXmlConverter );
}
Btw, you could do that with an interceptor too but not with the "IClientHttpRequestFactoryInterceptor" that intercepts request creation.
You should use instead "IClientHttpRequestBeforeInterceptor" that intercepts request execution.