RestAssured LogConfig.blacklistedHeaders error - rest-assured

I am getting below error when run serenity-cucumber6 test with rest-assured.
Step failed
java.lang.NoSuchMethodError: io.restassured.config.LogConfig.blacklistedHeaders()Ljava/util/Set;
at net.serenitybdd.rest.utils.RestReportingHelper.registerCall(RestReportingHelper.java:69)
at net.serenitybdd.rest.decorators.request.RequestSpecificationDecorated.reportQuery(RequestSpecificationDecorated.java:292)
at net.serenitybdd.rest.decorators.request.RequestSpecificationDecorated.execute(RequestSpecificationDecorated.java:284)
at net.serenitybdd.rest.decorators.request.RequestSpecificationDecorated.get(RequestSpecificationDecorated.java:67)
at net.serenitybdd.rest.decorators.request.RequestSpecificationDecorated.get(RequestSpecificationDecorated.java:38)
The versions I am using are:
<spring-boot.version>2.4.5</spring-boot.version>
<serenity.plugin.version>2.4.34</serenity.plugin.version>
<serenity.version>2.4.34</serenity.version>
<serenity.cucumber.version>2.4.34</serenity.cucumber.version>
<cucumber.version>6.10.4</cucumber.version>
<java.version>11</java.version>
The test main class
import org.junit.runner.RunWith;
import io.cucumber.junit.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
#RunWith(CucumberWithSerenity.class)
#CucumberOptions(
plugin = {"pretty", "html:target/reports/cucumber-html-report",
"html:target/cucumber-reports/cucumber-pretty",
"json:target/cucumber.json"},
tags = "not #skip",
glue = {"my.stepdefinitions"},
features = "src/it/resources/features/")
public class MyServiceCucumberTests {
}
Request call method
public static Response request(Function<RequestSpecification, Response> method, RequestSpecification spec) {
RequestSpecification call = rest()
.spec(spec)
.when();
return method.apply(call)
.then()
.extract().response();
}

Related

Testing a Feign Client

I've written a feign client and I would like to test that it works using a unit test.
For my case, integration tests is not the right approach for the current development stage.
The feign client is null, I receive a NullPointerException while running the test.
How can I autowire it?
Feign client
package com.myapp.clients;
import com.myapp.model.StatusResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#FeignClient(name="myClient", url="${feign.clients.my.url}")
public interface myClient {
#RequestMapping(method= RequestMethod.GET, value="/v1/users/{userId}")
StatusResponse getStatus(
#RequestHeader(value = "Auth", required = true) String authorizationHeader,
#RequestHeader(value = "my_tid", required = true) String tid,
#PathVariable("userId") String userId);
}
Tests:
package com.myapp.clients;
import com.intuit.secfraudshared.step.broker.model.StatusResponse;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class MyClientTest {
#Autowired
MyClient myClient;
#Test
public void testmyClient_status200() {
StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
Assert.assertNotNull(iusResponse);
}
}
How can autowire MyClient?
The method that has worked for me so far while trying to test Feign Clients is stubbing the response via wiremock. You would need to add dependency for wiremock.
testImplementation 'org.springframework.cloud:spring-cloud-contract-wiremock'
Then you would need to annotate as
#RunWith(SpringRunner.class)
#SpringBootTest(properties = "feign.clients.my.url=http://localhost:${wiremock.server.port}")
#AutoConfigureWireMock(port = 0)
And then stub using wiremock.
stubFor(post(urlPathMatching("/v1/users/([a-zA-Z0-9-]*)")).willReturn(aResponse().withStatus(200).withHeader("content-type", "application/json").withBody("{\"code\":200,\"status\":\"success\"})));
where ([a-zA-Z0-9-]*) is regex for {userId} assuming it is alphanumeric.
And then, of course, assert.
StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
Assert.assertNotNull(myResponse);

Can't override onAuthenticationSuccess method of AuthenticationSuccessHandler

Following some other posts, I tried to override the authentication success method of the spring-security handler, but it's never being called. My code looks like:
src/groovy/mypackage/MyAuthenticationSuccessHandler.groovy:
package mypackage
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
public MyAuthenticationSuccessHandler() {
println("constructed!")
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
println("override called")
super.onAuthenticationSuccess(request, response, authentication);
}
}
resources.groovy:
authenticationSuccessHandler(MyAuthenticationSuccessHandler) {
def conf = SpringSecurityUtils.securityConfig
requestCache = ref('requestCache')
defaultTargetUrl = conf.successHandler.defaultTargetUrl
alwaysUseDefaultTargetUrl = conf.successHandler.alwaysUseDefault
targetUrlParameter = conf.successHandler.targetUrlParameter
useReferer = conf.successHandler.useReferer
redirectStrategy = ref('redirectStrategy')
}
There are no errors, the constructor is definitely called and MyAuthenticationSuccessHandler is injected into a test controller, but onAuthenticationSuccess is never called. I dropped a breakpoint into the superclass version and that worked. I also tried rewriting my custom class in java but that didn't work.
What am I doing wrong?
Turns out another login filter was already active and it was preventing the normal method from working. The filter in question is org.mitre.openid.connect.client.OIDCAuthenticationFilter and the workaround is to inject your success handler through that one e.g.:
authenticationSuccessHandler(apipulse.MyAuthenticationSuccessHandler) {
clientRegistrationTemplate = ref(clientRegistrationTemplate)
}
...
openIdConnectAuthenticationFilter(OIDCAuthenticationFilter) {
...
authenticationSuccessHandler = ref('authenticationSuccessHandler')
}
Just wasted a day looking at this - thanks a bunch, spring.

Grails 3.3.8 : Unable to resolve ControllerUnitTest

I am attempting to write some basic controller tests and am following the documentation https://docs.grails.org/latest/guide/testing.html. My test currently is unable to find ControllerUnitTest. Is there a dependency that I am missing?
Here is my import
grails.testing.web.controllers.ControllerUnitTest
See the project at https://github.com/jeffbrown/mcroteaucontrollertest.
https://github.com/jeffbrown/mcroteaucontrollertest/blob/master/src/test/groovy/mcroteaucontrollertest/DemoControllerSpec.groovy
package mcroteaucontrollertest
import grails.testing.web.controllers.ControllerUnitTest
import spock.lang.Specification
import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED
class DemoControllerSpec extends Specification implements ControllerUnitTest<DemoController> {
void "test GET request"() {
when:
controller.index()
then:
response.text == 'Success'
}
void "test POST request"() {
when:
request.method = 'POST'
controller.index()
then:
response.status == METHOD_NOT_ALLOWED.value()
}
}
The ControllerUnitTest trait is provided by grails-web-testing-support. Make sure you have something like testCompile "org.grails:grails-web-testing-support" as shown at https://github.com/jeffbrown/mcroteaucontrollertest/blob/cf5f09b1c2efaba759f6513301d7b55fcb29979b/build.gradle#L56.

Get method does not return any response in RestAssured Java in eclipse

Can someone please help me here, below is the code:
package student.profile.picture;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
public class GetProfilePicture {
#Test
void Fetch()
{
RestAssured.baseURI="http://localhost:5100"; // giving base URI
Response res=given().
header("tenantId","Augusta-PT").
when().
get("/ProfilePicture").
then().assertThat().statusCode(200).extract().response();
String responsestring=res.asString();
System.out.println(responsestring);
/*JsonPath js = new JsonPath(responsestring);
String FileContentType = js.get("fileContentType");
String ExpectedFilecontenttype = "image/png";
System.out.println(FileContentType);
Assert.assertEquals(FileContentType, ExpectedFilecontenttype); */
}
}
It does not show any error, it is a simple get method to show response, nothing shows up in console.
Any help please?
It is recommended to break up your statement in two parts,
First, get the response,
RestAssured.baseURI = "http://localhost:5100";
Response res = given()
.header("tenantId","Augusta-PT")
.when()
.get("/ProfilePicture");
And second part to assert,
res.then()
.assertThat()
.statusCode(200);
System.out.println(res.asString());
This will solve your issue and you should be able to get the response in console.

Mock testing in Grails 2.0 errors

I've recently upgraded a Grails 1.3.7 project up to Grails 2.0.4 and noticed that many of my unit tests with mocking have started to fail. The Controller tests seem to pass just fine, the issue comes when you have Services collaborating with one another and try to mock out the calls to the collaborators. The strange part about it is if I run the single test, it passes, but as soon as I run the entire suite, they fail giving the error:
No more calls to 'getName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getName' expected at this point. End of demands.
I've even tried using GMock instead of new MockFor(), but get this very similar error:
No more calls to 'getSimpleName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getSimpleName' expected at this point. End of demands.
Here's a contrived example showing how to duplicate the errors I'm getting, and the entire sample project on GitHub at https://github.com/punkisdead/FunWithMocks. Any ideas of how to make this work?
BarController:
package funwithmocks
class BarController {
def barService
def fooService
def index() { }
}
BarService:
package funwithmocks
class BarService {
def fooService
def bazService
def serviceMethod() {
}
}
BarControllerTests:
package funwithmocks
import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor
/**
* See the API for {#link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
#TestFor(BarController)
class BarControllerTests {
def fooService
def barService
#Before
public void setUp() {
fooService = new MockFor(FooService)
fooService.use {
controller.fooService = new FooService()
}
barService = new MockFor(BarService)
barService.use {
controller.barService = new BarService()
}
}
#Test
void doSomething() {
controller.index()
}
}
BarServiceTests:
package funwithmocks
import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor
/**
* See the API for {#link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
*/
#TestFor(BarService)
class BarServiceTests {
def fooService
def bazService
#Before
public void setUp() {
fooService = new MockFor(FooService)
fooService.use {
service.fooService = new FooService()
}
bazService = new MockFor(BazService)
bazService.use {
service.bazService = new BazService()
}
}
#Test
void callSomeService() {
service.serviceMethod()
}
}
You shouldn't to combine the new test mixin with MockFor groovy class. Replace all MockFor instance with the mockFor method.
http://grails.org/doc/latest/guide/testing.html#mockingCollaborators

Resources