Need Junit test case of Bean method that is returning WebMvcEndpointHandlerMapping - spring

Need Junit test case of Bean method that is returning WebMvcEndpointHandlerMapping
Following is the code snippet.
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(
WebEndpointsSupplier webEndpointsSupplier,
ServletEndpointsSupplier servletEndpointsSupplier,
ControllerEndpointsSupplier controllerEndpointsSupplier,
EndpointMediaTypes endpointMediaTypes,
CorsEndpointProperties corsProperties,
WebEndpointProperties webEndpointProperties,
Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping =
this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(
endpointMapping,
webEndpoints,
endpointMediaTypes,
corsProperties.toCorsConfiguration(),
new EndpointLinksResolver(allEndpoints, basePath),
shouldRegisterLinksMapping,
null);
}
private boolean shouldRegisterLinksMapping(
WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled()
&& (StringUtils.hasText(basePath)
|| ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
I need a test case for method webEndpointServletHandlerMapping. Your help is really appreciable.

Related

Mockito, how to mock call by reference method on same class

Why I can not mock callRefMethod method (call method by reference) on below code? The problem is real method of callRefMethod always being called.
public class ManageUserService {
public void callRefMethod(List<String> lsStr, boolean flag){
if (flag){
lsStr.add("one");
lsStr.add("two");
}
}
public void methodA(){
List<String> lsStr = new ArrayList<>();
lsStr.add("zero");
this.callRefMethod(lsStr, true);
for(String str : lsStr){
System.out.println(str);
}
}
}
Unit tests:
public class ManageUserServiceTest {
#InjectMocks
private ManageUserService manageUserService;
private AutoCloseable closeable;
#BeforeEach
public void init() {
closeable = MockitoAnnotations.openMocks(this);
}
#AfterEach
void closeService() throws Exception {
closeable.close();
}
#Test
void methodATest(){
List<String> lsData = new ArrayList<>();
lsData.add("start");
ManageUserService manageUserServiceA = new ManageUserService();
ManageUserService userSpy = spy(manageUserServiceA);
doNothing().when(userSpy).callRefMethod(lsData, true);
userSpy.methodA();
verify(userSpy).callRefMethod(ArgumentMatchers.any(ArrayList.class), ArgumentMatchers.any(Boolean.class));
}
}
The result :
zero
one
two
The problem is the difference between the list you're creating in the test method, which is used to match the expected parameters when "doing nothing":
List<String> lsData = new ArrayList<>();
lsData.add("start");
...
doNothing().when(userSpy).callRefMethod(lsData, true);
and the list created in the tested method, passed to the spy object:
List<String> lsStr = new ArrayList<>();
lsStr.add("zero");
this.callRefMethod(lsStr, true);
You're telling Mockito to doNothing if the list is: ["start"], but such list is never passed to the callRefMethod. ["zero"] is passed there, which does not match the expected params, so actual method is called.
Mockito uses equals to compare the actual argument with an expected parameter value - see: the documentation. To work around that ArgumentMatchers can be used.
You can either fix the value added to the list in the test or match the expected parameter in a less strict way (e.g. using anyList() matcher).
ok i did it by using : where manageUserServiceOne is spy of ManageUserService class
void methodATest(){
List<String> lsData = new ArrayList<>();
lsData.add("start");
doAnswer((invocation) -> {
System.out.println(invocation.getArgument(0).toString());
List<String> lsModify = invocation.getArgument(0);
lsModify.add("mockA");
lsModify.add("mockB");
return null;
}).when(manageUserServiceOne).callRefMethod(anyList(), anyBoolean());
manageUserServiceOne.methodA();
verify(manageUserServiceOne).callRefMethod(ArgumentMatchers.any(ArrayList.class), ArgumentMatchers.any(Boolean.class));
}

Unit test in Spring boot using Mockito

While executing Juint4 test. it shows null pointer exception. while using save method in unit test it returns null. Here i am using Mockito Juint4 Testing to mock the method. someone help me out with this.
**Service Method.**
public Result save(Map inputParams){
Result result = new Result();
logger.info("::::::::::::::: save ::::::::::::::::"+inputParams);
try{
String name = inputParams.get("name").toString();
String type = inputParams.get("type").toString();
CoreIndustry coreIndustry = coreIndustryDao.findByName(name);
if(coreIndustry != null){
result.setStatusCode(HttpStatus.FOUND.value());
result.setMessage(Messages.NAME_EXIST_MESSAGE);
result.setSuccess(false);
}else{
CoreIndustry coreIndustryNew = new CoreIndustry();
coreIndustryNew.setName(name);
coreIndustryNew.setType(type);
coreIndustryNew.setInfo(new Gson().toJson(inputParams.get("info")));
System.out.println("CoreIndustry Info is :............:.............:..............:"+coreIndustryNew.getInfo());
CoreIndustry coreIndustryData = coreIndustryDao.save(coreIndustryNew);
System.out.println("Saved Data Is.............::::::::::::::::::::................ "+coreIndustryData.getName()+" "+coreIndustryData.getType()+" "+coreIndustryData.getType());
result.setData(coreIndustryData);
result.setStatusCode(HttpStatus.OK.value());
result.setMessage(Messages.CREATE_MESSAGE);
result.setSuccess(true);
}
}catch (Exception e){
logger.error("::::::::::::::: Exception ::::::::::::::::"+e.getMessage());
result.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
result.setSuccess(false);
result.setMessage(e.getMessage());
}
return result;
}
**Controller**
#PostMapping(path = "/industry/save")
public Result save(#RequestBody Map<String, Object> stringToParse) {
logger.debug("save---------------"+stringToParse);
Result result = industryService.save(stringToParse);
return result;
}
**Unit Test**
#RunWith(SpringRunner.class)
#SpringBootTest
public class IndustryServiceTest {
#MockBean
private CoreIndustryDao coreIndustryDao;
private IndustryService industryService;
#Test
public void getAll() {
System.out.println("::::::: Inside of GetAll Method of Controller.");
// when(coreIndustryDao.findAll()).thenReturn(Stream.of(
// new CoreIndustry("Dilip","Brik","Brik Industry"))
// .collect(Collectors.toList()));
//assertEquals(1,industryService.getAll().setData());
}
#Test
public void save() {
ObjectMapper oMapper = new ObjectMapper();
CoreIndustry coreIndustry = new CoreIndustry();
coreIndustry.setId(2L);
coreIndustry.setName("Dilip");
coreIndustry.setType("Business");
HashMap<String,Object> map = new HashMap();
map.put("name","Retail");
map.put("type","Development");
coreIndustry.setInfo(new Gson().toJson(map));
when(coreIndustryDao.save(any(CoreIndustry.class))).thenReturn(new CoreIndustry());
Map<String, Object> actualValues = oMapper.convertValue(coreIndustry,Map.class);
System.out.println("CoreIndustry Filed values are........ : "+coreIndustry.getName()+" "+coreIndustry.getInfo());
Result created = industryService.save(actualValues);
CoreIndustry coreIndustryValue = (CoreIndustry) created.getData();
Map<String, Object> expectedValues = oMapper.convertValue(coreIndustryValue, Map.class);
System.out.println(" Getting Saved data from CoreIndustry........"+expectedValues);
System.out.println(" Getting Saved data from CoreIndustry........"+coreIndustryValue.getName());
assertThat(actualValues).isSameAs(expectedValues);
}
I am new in this Spring boot Technology.
After Running the source code for save method.
After Debugging my source code..
It will be great please to help me out. Thank you.

How to reuse a scenario in citrus framework?

I set this testing scenario with citrus framework. Now I'm trying to reuse it in other scenarios.
I'm creating a behavior for each step. My behaviors are mainly http requests
public class NoProductDocumentValidationScenarioIT {
private #CitrusResource TestContext parentContext;
#CitrusEndpoint(name = "todoBasicAuthClient")
private HttpClient cmsAuthClient;
#CitrusEndpoint(name = "vdmBasicAuthClient")
private HttpClient vdmAuthClient;
#CitrusEndpoint(name = "gvHttpClient")
private HttpClient gvHttpClient;
#Test
#CitrusTest
public String NoProductDocumentValidation(#CitrusResource TestRunner runner, #CitrusResource TestContext context)
throws BadNewsMLG2Exception {
String pdtIdentifier = "EDIT-FR-SVID2-YM9N001479";
String videoDocument = VideoDocument.setUpVideoDocument("fr", "v1_afptv_sport_broadcast_photos");
int jobPublicationID = 5;
// CMS Authentification
TestBehavior authenticateCMS = new ProductAuthenticationBehavior(cmsAuthClient);
ApplyTestBehaviorAction authenticateActionCMS = new ApplyTestBehaviorAction(runner, authenticateCMS);
authenticateActionCMS.doExecute(context);
// Document Creation
CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
videoDocument);
ApplyTestBehaviorAction createDocAction = new ApplyTestBehaviorAction(runner, createDoc);
createDocAction.doExecute(context);
// get document data
videoDocument = createDoc.getVideoDocument();
G2VideoDocument g2VideoDocument = ((G2VideoDocument) G2ObjectFactory.parse(videoDocument));
g2VideoDocument.getProducts();
String linkToVideoDocument = g2VideoDocument.getLinkToSelf().toString();
String linkToProject = g2VideoDocument.getLinkToVideoProject().toString();
String projectID = IrisStringTools.extractIdFromUri(linkToProject);
String documentID = IrisStringTools.extractIdFromUri(linkToVideoDocument);
String etag = g2VideoDocument.getEditorialTag();
// Lock document Metadata
EditVideoDocumentMetaBehavior lockDocMeta = new EditVideoDocumentMetaBehavior(cmsAuthClient, pdtIdentifier,
videoDocument, documentID);
ApplyTestBehaviorAction lockDocMetaAction = new ApplyTestBehaviorAction(runner, lockDocMeta);
lockDocMetaAction.doExecute(context);
}
}
I run this in eclipse as JUnit test.
I thought about using a super class but it didn't work.
public class ProductDocumentValidationScenarioIT extends NoProductDocumentValidationScenarioIT {
public String ProductDocumentValidation(#CitrusResource TestRunner runner, #CitrusResource TestContext context)
throws BadNewsMLG2Exception {
return something;
}
}
Test behaviors is the way to go here. I suggest to use something like this
CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
videoDocument);
runner.applyBehavior(createDoc);
what we finally did is to create a behavior runner (a java class) where all the behaviors are instanciated and then in the scenario we call the behavior runner with the behavior constant corresponding to the behavior I need:
public class BehaviorRunner {
private void doExecute(TestRunner runner, TestContext context, TestBehavior testBehavior) {
ApplyTestBehaviorAction behaviorAction = new ApplyTestBehaviorAction(runner,testBehavior);
behaviorAction.doExecute(context);
}
public void execute( String behaviorLabel, #CitrusResource TestRunner runner, #CitrusResource TestContext context) {
try {
switch (behaviorLabel) {
case BehaviorConstants.CREATE_VIDEO_DOCUMENT :
CreateVideoDocumentBehavior createVideoDocumentBehavior = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier, VideoDocument.setUpVideoDocument2(LanguageConstants.EN, "v1_afptv_sport_broadcast_photos"));
doExecute(runner, context, createVideoDocumentBehavior);
break;
case BehaviorConstants.MOVIEDRAFT :
MovieDraftDocumentBehavior movieDraftDocumentBehavior = new MovieDraftDocumentBehavior(cmsAuthClient, pdtIdentifier, 1, g2VideoDoc);
doExecute(runner, context, movieDraftDocumentBehavior);
break;
case BehaviorConstants.PUBLICATION_PROGRESSION_STATUS:
GetPublicationProgressionStatusBehavior publicationProgressionStatusBehavior = new GetPublicationProgressionStatusBehavior(vdmAuthClient, pdtIdentifier , g2VideoDoc);
doExecute(runner, context, publicationProgressionStatusBehavior);
break;
case BehaviorConstants.VALIDATE :
ValidateDocumentBehavior validateDocumentBehavior = new ValidateDocumentBehavior(cmsAuthClient, pdtIdentifier, g2VideoDoc);
doExecute(runner, context, validateDocumentBehavior);
break;
default:
break;
}
we ended up with a scenario like this:
#Test
#CitrusTest
public void NoProductDocumentValidation(#CitrusResource TestRunner runner, #CitrusResource TestContext context) throws BadNewsMLG2Exception {
slf4jLogger.info("Montage analysis scenario START");
// execute scenario
// Document Creation
behaviorRunner.execute(BehaviorConstants.CREATE_VIDEO_DOCUMENT, runner, context);
// Lock document Metadata
behaviorRunner.execute(BehaviorConstants.EDITOR, runner, context);
// Lock Document Binary
behaviorRunner.execute(BehaviorConstants.BINARY_EDITOR, runner, context);
That saved us a lot of code lines since we're using different combinations of behaviors in different scenarios.
I hope this would help someone!

Template variables with ControllerLinkBuilder

I want my response to include this:
"keyMaps":{
"href":"http://localhost/api/keyMaps{/keyMapId}",
"templated":true
}
That's easy enough to achieve:
add(new Link("http://localhost/api/keyMaps{/keyMapId}", "keyMaps"));
But, of course, I'd rather use the ControllerLinkBuilder, like this:
add(linkTo(methodOn(KeyMapController.class).getKeyMap("{keyMapId}")).withRel("keyMaps"));
The problem is that by the time the variable "{keyMapId}" reaches the UriTemplate constructor, it's been included in an encoded URL:
http://localhost/api/keyMaps/%7BkeyMapId%7D
So UriTemplate's constructor doesn't recognise it as containing a variable.
How can I persuade ControllerLinkBuilder that I want to use template variables?
It looks to me like the current state of Spring-HATEOAS doesn't allow this via the ControllerLinkBuilder (I'd very much like to be proven wrong), so I have implemented this myself using the following classes for templating query parameters:
public class TemplatedLinkBuilder {
private static final TemplatedLinkBuilderFactory FACTORY = new TemplatedLinkBuilderFactory();
public static final String ENCODED_LEFT_BRACE = "%7B";
public static final String ENCODED_RIGHT_BRACE = "%7D";
private UriComponentsBuilder uriComponentsBuilder;
TemplatedLinkBuilder(UriComponentsBuilder builder) {
uriComponentsBuilder = builder;
}
public static TemplatedLinkBuilder linkTo(Object invocationValue) {
return FACTORY.linkTo(invocationValue);
}
public static <T> T methodOn(Class<T> controller, Object... parameters) {
return DummyInvocationUtils.methodOn(controller, parameters);
}
public Link withRel(String rel) {
return new Link(replaceTemplateMarkers(uriComponentsBuilder.build().toString()), rel);
}
public Link withSelfRel() {
return withRel(Link.REL_SELF);
}
private String replaceTemplateMarkers(String encodedUri) {
return encodedUri.replaceAll(ENCODED_LEFT_BRACE, "{").replaceAll(ENCODED_RIGHT_BRACE, "}");
}
}
and
public class TemplatedLinkBuilderFactory {
private final ControllerLinkBuilderFactory controllerLinkBuilderFactory;
public TemplatedLinkBuilderFactory() {
this.controllerLinkBuilderFactory = new ControllerLinkBuilderFactory();
}
public TemplatedLinkBuilder linkTo(Object invocationValue) {
ControllerLinkBuilder controllerLinkBuilder = controllerLinkBuilderFactory.linkTo(invocationValue);
UriComponentsBuilder uriComponentsBuilder = controllerLinkBuilder.toUriComponentsBuilder();
Assert.isInstanceOf(DummyInvocationUtils.LastInvocationAware.class, invocationValue);
DummyInvocationUtils.LastInvocationAware invocations = (DummyInvocationUtils.LastInvocationAware) invocationValue;
DummyInvocationUtils.MethodInvocation invocation = invocations.getLastInvocation();
Object[] arguments = invocation.getArguments();
MethodParameters parameters = new MethodParameters(invocation.getMethod());
for (MethodParameter requestParameter : parameters.getParametersWith(RequestParam.class)) {
Object value = arguments[requestParameter.getParameterIndex()];
if (value == null) {
uriComponentsBuilder.queryParam(requestParameter.getParameterName(), "{" + requestParameter.getParameterName() + "}");
}
}
return new TemplatedLinkBuilder(uriComponentsBuilder);
}
}
Which embeds the normal ControllerLinkBuilder and then uses similar logic to parse for #RequestParam annotated parameters that are null and add these on to the query parameters. Also, our client resuses these templated URIs to perform further requests to the server. To achieve this and not need to worry about stripping out the unused templated params, I have to perform the reverse operation (swapping {params} with null), which I'm doing using a custom Spring RequestParamMethodArgumentResolver as follows
public class TemplatedRequestParamResolver extends RequestParamMethodArgumentResolver {
public TemplatedRequestParamResolver() {
super(false);
}
#Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
Object value = super.resolveName(name, parameter, webRequest);
if (value instanceof Object[]) {
Object[] valueAsCollection = (Object[])value;
List<Object> resultList = new LinkedList<Object>();
for (Object collectionEntry : valueAsCollection) {
if (nullifyTemplatedValue(collectionEntry) != null) {
resultList.add(collectionEntry);
}
}
if (resultList.isEmpty()) {
value = null;
} else {
value = resultList.toArray();
}
} else{
value = nullifyTemplatedValue(value);
}
return value;
}
private Object nullifyTemplatedValue(Object value) {
if (value != null && value.toString().startsWith("{") && value.toString().endsWith("}")) {
value = null;
}
return value;
}
}
Also this needs to replace the existing RequestParamMethodArgumentResolver which I do with:
#Configuration
public class ConfigureTemplatedRequestParamResolver {
private #Autowired RequestMappingHandlerAdapter adapter;
#PostConstruct
public void replaceArgumentMethodHandlers() {
List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(adapter.getArgumentResolvers());
for (int cursor = 0; cursor < argumentResolvers.size(); ++cursor) {
HandlerMethodArgumentResolver handlerMethodArgumentResolver = argumentResolvers.get(cursor);
if (handlerMethodArgumentResolver instanceof RequestParamMethodArgumentResolver) {
argumentResolvers.remove(cursor);
argumentResolvers.add(cursor, new TemplatedRequestParamResolver());
break;
}
}
adapter.setArgumentResolvers(argumentResolvers);
}
}
Unfortunately, although { and } are valid characters in a templated URI, they are not valid in a URI, which may be a problem for your client code depending on how strict it is. I'd much prefer a neater solution built into Spring-HATEOAS!
With latest versions of spring-hateoas you can do the following:
UriComponents uriComponents = UriComponentsBuilder.fromUri(linkBuilder.toUri()).build();
UriTemplate template = new UriTemplate(uriComponents.toUriString())
.with("keyMapId", TemplateVariable.SEGMENT);
will give you: http://localhost:8080/bla{/keyMapId}",
Starting with this commit:
https://github.com/spring-projects/spring-hateoas/commit/2daf8aabfb78b6767bf27ac3e473832c872302c7
You can now pass null where path variable is expected. It works for me, without workarounds.
resource.add(linkTo(methodOn(UsersController.class).someMethod(null)).withRel("someMethod"));
And the result:
"someMethod": {
"href": "http://localhost:8080/api/v1/users/{userId}",
"templated": true
},
Also check related issues: https://github.com/spring-projects/spring-hateoas/issues/545
We've run into the same problem. General workaround is we have our own LinkBuilder class with a bunch of static helpers. Templated ones look like this:
public static Link linkToSubcategoriesTemplated(String categoryId){
return new Link(
new UriTemplate(
linkTo(methodOn(CategoryController.class).subcategories(null, null, categoryId))
.toUriComponentsBuilder().build().toUriString(),
// register it as variable
getBaseTemplateVariables()
),
REL_SUBCATEGORIES
);
}
private static TemplateVariables getBaseTemplateVariables() {
return new TemplateVariables(
new TemplateVariable("page", TemplateVariable.VariableType.REQUEST_PARAM),
new TemplateVariable("sort", TemplateVariable.VariableType.REQUEST_PARAM),
new TemplateVariable("size", TemplateVariable.VariableType.REQUEST_PARAM)
);
}
This is for exposing the parameters of a controller response of a PagedResource.
then in the controllers we call this an append a withRel as needed.
According to this issue comment, this will be addressed in an upcoming release of spring-hateoas.
For now, there's a drop-in replacement for ControllerLinkBuilder available from de.escalon.hypermedia:spring-hateoas-ext in Maven Central.
I can now do this:
import static de.escalon.hypermedia.spring.AffordanceBuilder.*
...
add(linkTo(methodOn(KeyMapController.class).getKeyMap(null)).withRel("keyMaps"));
I pass in null as the parameter value to indicate I want to use a template variable. The name of the variable is automatically pulled from the controller.
I needed to include a link with template variables in the root of a spring data rest application, to get access via traverson to an oauth2 token. This is working fine, maybe useful:
#Component
class RepositoryLinksResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
#Override
RepositoryLinksResource process(RepositoryLinksResource resource) {
UriTemplate uriTemplate = new UriTemplate(
ControllerLinkBuilder.
linkTo(
TokenEndpoint,
TokenEndpoint.getDeclaredMethod("postAccessToken", java.security.Principal, Map )).
toUriComponentsBuilder().
build().
toString(),
new TemplateVariables([
new TemplateVariable("username", TemplateVariable.VariableType.REQUEST_PARAM),
new TemplateVariable("password", TemplateVariable.VariableType.REQUEST_PARAM),
new TemplateVariable("clientId", TemplateVariable.VariableType.REQUEST_PARAM),
new TemplateVariable("clientSecret", TemplateVariable.VariableType.REQUEST_PARAM)
])
)
resource.add(
new Link( uriTemplate,
"token"
)
)
return resource
}
}
Based on the previous comments I have implemented a generic helper method (against spring-hateoas-0.20.0) as a "temporary" workaround. The implementation does consider only RequestParameters and is far from being optimized or well tested. It might come handy to some other poor soul traveling down the same rabbit hole though:
public static Link getTemplatedLink(final Method m, final String rel) {
DefaultParameterNameDiscoverer disco = new DefaultParameterNameDiscoverer();
ControllerLinkBuilder builder = ControllerLinkBuilder.linkTo(m.getDeclaringClass(), m);
UriTemplate uriTemplate = new UriTemplate(UriComponentsBuilder.fromUri(builder.toUri()).build().toUriString());
Annotation[][] parameterAnnotations = m.getParameterAnnotations();
int param = 0;
for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if (annotation.annotationType().equals(RequestParam.class)) {
RequestParam rpa = (RequestParam) annotation;
String parameterName = rpa.name();
if (StringUtils.isEmpty(parameterName)) parameterName = disco.getParameterNames(m)[param];
uriTemplate = uriTemplate.with(parameterName, TemplateVariable.VariableType.REQUEST_PARAM);
}
}
param++;
}
return new Link(uriTemplate, rel);
}

ActionContext.getContext().getParameters() returns null during StrutsJUnit4TestCase

I am running a JUnit test via maven where a struts action java method is being tested that makes the following call:
// Gets this from the "org.apache.struts2.util.TokenHelper" class in the struts2-core jar
String token = TokenHelper.getTokenName();
Here is the method in "TokenHelper.java":
/**
* Gets the token name from the Parameters in the ServletActionContext
*
* #return the token name found in the params, or null if it could not be found
*/
public static String getTokenName() {
Map params = ActionContext.getContext().getParameters();
if (!params.containsKey(TOKEN_NAME_FIELD)) {
LOG.warn("Could not find token name in params.");
return null;
}
String[] tokenNames = (String[]) params.get(TOKEN_NAME_FIELD);
String tokenName;
if ((tokenNames == null) || (tokenNames.length < 1)) {
LOG.warn("Got a null or empty token name.");
return null;
}
tokenName = tokenNames[0];
return tokenName;
}
The 1st line in this method is returning null:
Map params = ActionContext.getContext().getParameters();
The next LOC down, "params.containKey(...)" throws a NullPointerException because "params" is null.
When this action is called normally, this runs fine. However, during the JUnit test, this Null Pointer occurs.
My test class looks like this:
#Anonymous
public class MNManageLocationActionTest extends StrutsJUnit4TestCase {
private static MNManageLocationAction action;
#BeforeClass
public static void init() {
action = new MNManageLocationAction();
}
#Test
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/companylocation/FetchCountyListByZip.action");
assertNotNull(mapping);
}
#Test
public void testLoadStateList() throws JSONException {
request.setParameter("Ryan", "Ryan");
String result = action.loadStateList();
assertEquals("Verify that the loadStateList() function completes without Exceptions.",
result, "success");
}
}
The ActionContext.getContext() is at least no longer null after I switched to using StrutsJUnit4TestCase.
Any idea why .getParameters() is returning null?
You need to initialize parameters map by yourself inside your test method. Additionally if you want to get token name you need to put it in parameters map.
Map<String, Object> params = new HashMap<String, Object>();
params.put(TokenHelper.TOKEN_NAME_FIELD,
new String[] { TokenHelper.DEFAULT_TOKEN_NAME });
ActionContext.getContext().setParameters(params);

Resources