I am currently trying to create expectations and get them verified by mockServer (can be found here).
I've read their documentation several times now but I can't find out why the verifcation of my expectation fails.
This is my code
#Rule
public MockServerRule mockServerRule = new MockServerRule(this, 9000);
private MockServerClient mockServer;
#Test
public void testVerification() {
mockServer.when(
HttpRequest.request()
.withMethod("POST")
.withPath("/validate")
.withHeader("\"Content-type\", \"application/json\"")
.withBody("{username: 'foo', password: 'bar'}"))
.respond(
HttpResponse.response()
.withStatusCode(401)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400"))
.withBody("{ message: 'incorrect username and password combination' }")
.withDelay(TimeUnit.SECONDS,1)
);
mockServer.verify(HttpRequest.request().withMethod("POST")
.withPath("/validate")
.withBody("{username: 'foo', password: 'bar'}"),
VerificationTimes.exactly(1));
}
When trying to verify, I always get the error
java.lang.AssertionError: Request not found exactly once, expected:<{
"method" : "POST",
"path" : "/validate",
"body" : "{username: 'foo', password: 'bar'}"}> but was:<>
at org.mockserver.client.server.MockServerClient.verify(MockServerClient.java:267)
at it.HttpTest.testVerification(HttpTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.mockserver.junit.MockServerRule$1.evaluate(MockServerRule.java:107)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Well, you forgot to send a request to your mock server. You only mocked its behaviour and then you check if the server has been called, but you missed the call.
Try it with something like this:
public int callValidateUrl() throws IOException {
URL url = new URL("http://localhost:9000/validate");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
String jsonInputString = "{username: 'foo', password: 'bar'}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
return con.getResponseCode();
}
If you are using Spring, RestTemplate is easier to use.
Related
I want test con Mockito, My controller gets 3 String, 1 File, 1 class
#RequestMapping(value = "/insertExcel", method = RequestMethod.POST, consumes = "multipart/form-data")
#ResponseBody
public MyMessage insertExcel(#RequestPart("period") String period, #RequestPart("commentary") String commentary,
#RequestPart("idProcess") String idProcess, #RequestPart("uploadFile") MultipartFile multipart,
#RequestPart("dataUser") DataUser dataUser) {
return this.mlService.insertFile(multipart, dataUser, idProcess, period, commentary);
}
Then I want simulate this with mockito:
MockMultipartFile file1 = new MockMultipartFile("period", "202001", "text/plain", "202001".getBytes());
MockMultipartFile file2 = new MockMultipartFile("commentary", "comentario", "text/plain", "comentario".getBytes());
MockMultipartFile file3 = new MockMultipartFile("idProcess", "process1", "text/plain", "process1".getBytes());
MockMultipartFile file4 = new MockMultipartFile("uploadFile", "uploadFile", "text/plain", "uploadFile".getBytes());
MockMultipartFile file5 = new MockMultipartFile("dataUser", "as", "text/plain", "{\"createDate\": \"2020\", \"createUser\": \"test\", \"modificationDate\":\"2020\", \"modificationUser\": \"test\" }".getBytes()) ;
this.webMvcMock.perform(MockMvcRequestBuilders.fileUpload("/ml/insertExcel")
.file(file1)
.file(file2)
.file(file3)
.file(file4)
.file(file5)).
andExpect(status().isOk());
Error:
java.lang.AssertionError: Status expected:<200> but was:<415>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
When I run this, I get error 415 why ??
How can I send the data correctly? Thanks
Edit:
I think what I get error 415 because in my controller I have consumes = "multipart/form-data"), so, I add in my test :
this.webMvcMock.perform((RequestBuilder) ((ResultActions) ((MockMultipartHttpServletRequestBuilder) ((MockMultipartHttpServletRequestBuilder) ((MockMultipartHttpServletRequestBuilder) ((MockMultipartHttpServletRequestBuilder) MockMvcRequestBuilders.fileUpload("/ml/insertExcel")
.file(file1).contentType(MediaType.MULTIPART_FORM_DATA))
.file(file2).contentType(MediaType.MULTIPART_FORM_DATA))
.file(file3).contentType(MediaType.MULTIPART_FORM_DATA))
.file(file4).contentType(MediaType.MULTIPART_FORM_DATA))
.file(file5).contentType(MediaType.MULTIPART_FORM_DATA)).
andExpect(status().isOk()));
Now the new error is:
java.lang.ClassCastException: org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder cannot be cast to org.springframework.test.web.servlet.ResultActions
at es.ApplicationTests.insertExcel1(ApplicationTests.java:497)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Edit2:
I modified the call to controller but I now other error:
MockMultipartFile file1 = new MockMultipartFile("period", "202001", "text/plain", "202001".getBytes());
MockMultipartFile file2 = new MockMultipartFile("commentary", "comentario", "text/plain", "comentario".getBytes());
MockMultipartFile file3 = new MockMultipartFile("idProcess", "process1", "text/plain", "process1".getBytes());
MockMultipartFile file4 = new MockMultipartFile("uploadFile", "uploadFile", "text/plain", "uploadFile".getBytes());
MockMultipartFile file5 = new MockMultipartFile("dataUser", "", "text/plain", "{\"createDate\": \"2020\", \"createUser\": \"test\", \"modificationDate\":\"2020\", \"modificationUser\": \"test\" }".getBytes()) ;
MockHttpServletRequestBuilder request = post("/ml/insertExcel");
request.content(file1.getBytes());
request.content(file2.getBytes());
request.content(file3.getBytes());
request.content(file4.getBytes());
request.content(file5.getBytes());
request.accept(MediaType.MULTIPART_FORM_DATA);
request.contentType(MediaType.MULTIPART_FORM_DATA);
this.webMvcMock.perform(request).andExpect(status().isOk());
The now error is 400:
java.lang.AssertionError: Status expected:<200> but was:<400>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
I don't care how to do it, but I need you to fill in the data to the controller
I'm relatively new to Testing in Mockito, and I'm trying to write few test cases for Controller level testing and I'm getting Null pointer Exception when I'm running the test case. I'm Injecting mocks at controller layer and mocking the service layer methods. Please let me know, the issue
Controller Class:
#RestController
#RequestMapping(value="v1.0/authentication")
public class OauthTokenController {
//Logging
private static final Logger LOG = LoggerFactory.getLogger(OauthTokenController.class);
#Autowired
private SsasServiceImpl ssasService;
#RequestMapping(value="/oauth/token", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public TokenActivationResponse grantToken(#RequestParam("username") String username, #RequestParam("password") String password, #RequestParam("grant_type") String grant_type){
TokenActivationResponse tokenActivationResponse = new TokenActivationResponse();
SecureString passwordSecured = new SecureString(password);
try{
tokenActivationResponse = ssasService.grantToken(username, passwordSecured, grant_type);
if(tokenActivationResponse == null){
throw new Exception();
}
LOG.info("Printing the response " + tokenActivationResponse);
}catch(Exception e){
LOG.error("Exception in oauth token granting controller", e);
}
return tokenActivationResponse;
}
}
SSASServiceImpl:
public class SSASServiceImpl{
public TokenActivationResponse grantToken(String username, SecureString password, String grant_type) throws IdvException {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add(USERNAME, username);
body.add(PASSWORD, (password != null) ? String.valueOf(password.getContent()) : null);
body.add(GRANT_TYPE, grant_type);
com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse tokenResponse = new com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse();
TokenActivationResponse response = new TokenActivationResponse();
tokenResponse = restProxy.sendAndReceiveToRestService(body, TOKEN, HttpMethod.POST, com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse.class);
response = transformGrantTokenResp(tokenResponse);
return response;
}
public TokenActivationResponse transformGrantTokenResp(com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse response) throws IdvException {
if (response != null) {
TokenActivationResponse resp = new TokenActivationResponse();
resp.getData().getAttributes().setAccess_token(response.getAccess_token());
resp.getData().getAttributes().setToken_type(response.getToken_type());
resp.getData().getAttributes().setExpires_in(response.getExpires_in());
resp.getData().getAttributes().setScope(response.getScope());
return resp;
} else {
IdvError error = new IdvError();
error.setTitle("Token Error");
throw new IdvException(error);
}
}
}
Test Class:
#RunWith(MockitoJUnitRunner.class)
public class OauthTokenControllerTest {
String accessToken = "d6234595-812d-40fc-b519-2e3456543";
Long expiresIn = 2905L;
String userName = "abcd";
String password = "efghijk";
String grant_type = "password";
String tokenType = "bearer";
String scope = "read write";
#Mock
SsasServiceImpl ssasService = new SsasServiceImpl();
#InjectMocks
OauthTokenController controller = new OauthTokenController();
#Before
public void setUp(){
}
TokenActivationResponse resp = new TokenActivationResponse();
#Test
public void testGrantToken() throws IdvException {
resp.getData().getAttributes().setAccess_token(accessToken);
resp.getData().getAttributes().setToken_type(tokenType);
resp.getData().getAttributes().setExpires_in(expiresIn);
resp.getData().getAttributes().setScope(scope);
SecureString sec = new SecureString(password);
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
assertNotNull(response);
}
}
Exception:
Connected to the target VM, address: '127.0.0.1:60951', transport: 'socket'
16:21:38.387 [main] ERROR com.idv.gateway.controller.OauthTokenController - Exception in oauth token granting controller
java.lang.Exception: null
at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:33)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Disconnected from the target VM, address: '127.0.0.1:60951', transport: 'socket'
[MockitoHint] OauthTokenControllerTest.testGrantToken (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:60)
[MockitoHint] ...args ok? -> at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:31)
Process finished with exit code -1
I've resolved the issue:
Solution and Fix:
In my TestCase Code, I've replaced the below any(String.class):
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
With (anyString()):
Mockito.when(ssasService.grantToken(anyString(),any(SecureString.class),anyString() )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(anyString(),any(String.class),anyString());
One of these Links hepled: Mockito - Invalid use of argument matchers
Also, if you use argument matcher in mockito for one argument, make sure to use for all.
I have a problem with my Unit Tests for a spring Rest application. In my Unit Tests I always get the problem that I get 401 "Unauthorized" as responsestatus and I don't know how to solve this problem.
My Security config is this:
#Configuration
#EnableWebSecurity
#Order(1)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApiKeyRepository apiKeyRepository;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
ApiKeyAuthFilter filter = new ApiKeyAuthFilter(Globals.HEADER_APIKEY);
filter.setAuthenticationManager(authentication -> {
String principal = (String) authentication.getPrincipal();
Optional<ApiKey> apiKey = apiKeyRepository.findByApiKey(principal);
if (!apiKey.isPresent()) {
throw new BadCredentialsException("The API key was not found or not the expected value.");
}
authentication.setAuthenticated(true);
return authentication;
});
httpSecurity.
csrf().disable().
addFilter(filter).authorizeRequests().anyRequest().authenticated().and().
regexMatcher("(?i)/api/v1/(?:print|resource)(?:/|$).*").
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
My Unit Test looks like:
#RunWith(SpringRunner.class)
#WebMvcTest(ResourceController.class)
public class ResourceControllerTestGetByLogicalFileNameOrDate {
#Autowired
private MockMvc mvc;
#Autowired
private ResourceRepository resourceRepositoryMock;
private Resource setNewResource(long fileSize, String hash, String logicalFileName) {
return getResource(fileSize, hash, logicalFileName);
}
#Test
public void testGetResourceByLogicalFileNameOrDateWithNoInput() throws Exception {
mvc.perform(get(String.format("/api/v1/resource/find/%s", ""))
.header(Globals.HEADER_APIKEY, "lEcsQI09MjUTCMQ5IVvSjf4Anxt+c4nhZAMnU1yDmVI=")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
I always get the problem that my tests failed. As response I get:
2018-05-07 09:26:52.003 INFO 18692 --- [ main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2018-05-07 09:26:52.003 INFO 18692 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2018-05-07 09:26:52.005 INFO 18692 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 2 ms
java.lang.AssertionError: Status
Expected :400
Actual :401
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at at.techsoft.iprint.nano.services.resource.ResourceControllerTestGetByLogicalFileNameOrDate.testGetResourceByLogicalFileNameOrDateWithNoInput(ResourceControllerTestGetByLogicalFileNameOrDate.java:83)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Can i turn off the security for the tests? Please can anyone help me to solve this.
When I use the Annotation #ActiveProfiles(value = "test") I get the Exception:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/resource/find
Parameters = {logicalFileName=[Res]}
Headers = {Content-Type=[application/json], X-NANO-APIKEY=[]}
Body = <no character encoding set>
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/api/v1/resource/find?logicalFileName=Res]}
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 = 401
Error message = Unauthorized
Headers = {WWW-Authenticate=[Basic realm="Realm"], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :401
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at at.techsoft.iprint.nano.services.resource.ResourceControllerTestGetByLogicalFileNameOrDate.testGetResourceByLogicalFileNameOrDateWithCorrectLogicalFileName(ResourceControllerTestGetByLogicalFileNameOrDate.java:88)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Since I use Spring Boot 1, I solved it this way:
#WebMvcTest(value = ResourceController.class, secure = false)
Please note that for the newer version of Spring Boot 2 the secure option is not available anymore, so use this:
#WebMvcTest(value = ResourceController.class, excludeAutoConfiguration = {SecurityAutoConfiguration.class})
Looks like your security is the one causes issue. You can use Spring Profile( like #Profile("Production")) as follows:
#Configuration
#EnableWebSecurity
#Profile("Production")
#Order(1)
public class ApiSecurityConfig{
...
}
#RunWith(SpringRunner.class)
#WebMvcTest(ResourceController.class)
#ActiveProfile("test")
public class ResourceControllerTestGetByLogicalFileNameOrDate {
...
}
Reference : https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html
Since in local tests you wouldn't want that to be configured, you can use #ActiveProfiles("test") while running the tests. this way, the configurations won't be loaded for local tests.
I have a service that returns a zip file. It works fine in dev/prod, a simple a GET /content/{id}/zip will download the file in my browser.
#GetMapping(value = "/content/{id}/zip")
public ResponseEntity<byte[]> getContentZip(#PathVariable String id) {
byte[] zip = ...
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
ResponseEntity<byte[]> response = new ResponseEntity<>(zip, headers, HttpStatus.OK);
return response;
}
The problem is with the test:
...
MvcResult result = restStudyMockMvc.perform(get("/content/{id}/zip", content.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType("application/zip")).andReturn();
byte[] bytes = result.getResponse().getContentAsByteArray();
assertThat(bytes).isNotEmpty();
...
It works fine with spring boot 1.5.
Since I've upgraded to spring boot 2. It gives me a "Could not find acceptable representation" exception:
11:04:21.244 [main] DEBUG i.o.v.web.ExceptionControllerAdvice - org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:287)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:218)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:166)
at io.osimis.vsol.web.StudyTest.getStudyZip(StudyTest.java:376)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
Thanks for your help :)
Maybe this is a little late, but I just had the same error and I found this question while searching for the solution.
In my case the error was that I had manually registered a HttpMessageConverter in my test.
this.mockMvc = MockMvcBuilders
...
.setMessageConverters(myJsonHttpMessageConverter)
.build();
By debugging I found out that the internal logic of Spring Mvc is:
If there is a converter configured, use only this converter.
If there is none configured, add all default converters.
Here is the relevant code from org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport:
protected final List<HttpMessageConverter<?>> getMessageConverters() {
if (this.messageConverters == null) {
this.messageConverters = new ArrayList<>();
configureMessageConverters(this.messageConverters);
if (this.messageConverters.isEmpty()) {
addDefaultHttpMessageConverters(this.messageConverters);
}
extendMessageConverters(this.messageConverters);
}
return this.messageConverters;
}
So to solve this you could either remove your custom converter so all default converters are used or - if you need it like I did - add the ByteArrayHttpMessageConverter in your test setup.
this.mockMvc = MockMvcBuilders
...
.setMessageConverters(myJsonHttpMessageConverter, new ByteArrayHttpMessageConverter())
.build();
I have postman body as attached in the image
I am trying to call restTemplate as follows.
String body= "client_id=admin-cli&username=abc&password=root&grant_type=password";
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl("no-cache");
headers.set("content-type", "application/x-www-form-urlencoded");
HttpEntity<String> request = new HttpEntity<String>(body, headers);
ResponseEntity<String> response = new RestTemplate().postForEntity(url, request, String.class);
But seems like body should not be simple string (with "&" in between values, as I am doing now). Any leads how to parse the body for the shown string in image?
Here goes the stack trace:
java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:74)
at org.springframework.web.client.RestTemplate.<init>(RestTemplate.java:179)
at io.opensaber.registry.authorization.AuthorizationFilterTest.test_valid_token(AuthorizationFilterTest.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 27 more
P.S. I found the issue and resolved. It was related to version incompatibility of jackson dependency.
You can put the params into the HttpEntity as a Map. See example below.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setCacheControl("no-cache");
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
params.add("client_id", "admin-cli");
params.add("username", "abc");
params.add("password", "root");
params.add("grant_type", "password");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);