how to Mock xyz.capybara.clamav.commands.scan.result.ScanResult getStatus Method - junit

Following is the Code I have:
ClamavClient client = new ClamavClient(clamdHost, clamdPort);
ScanResult result = client.scan(inputStream);
String status = result.getStatus().toString();
I want to Mock "result.getStatus()". I am using PowerMockito to Mock ScanResult
ScanResult mockScanResult = Mockito.mock(ScanResult.class);
when(mockClamavClient.scan(mockFileInputStream)).thenReturn(mockScanResult);
Does anyone know the answer, appreciate your help in advance.

The scan method is final so can't be mocked.

Related

JUnit Mockito returning LinkedList instead of ArrayList

I have been tasked to figure out why this JUnit Test is failing. What I have found is that instead of returning an ArrayList (like the getDeligationsForLoggedInUser is SUPPOSED to return, it returns a LinkedList for "userList".
#SuppressWarnings("unchecked")
#Test
public void test_getDelegationsForLoggedInUser()
{
String userId="Abcd";
List<String> expectedUserList= new ArrayList<String>();
expectedUserList.add("efghi");
expectedUserList.add("jklmn");
expectedUserList.add("opqrs");
when(namedParameterJdbcTemplate.queryForObject(anyString(),anyMap(), any(RowMapper.class))).thenReturn(expectedUserList);
List<String> userList= workflowProcessDAOImpl.getDelegationsForLoggedInUser(userId);
verify(namedParameterJdbcTemplate, times(1)).query(sqlCaptor.capture(), namedParameterMap.capture(), rowMapperCaptor.capture());
assertThat(userList, is(expectedUserList));
assertThat(sqlCaptor.getValue(), is(SQLConstantsSysConfigV1.getInstance().GET_USERIDS_FOR_DELEGATES));
}
Does anyone have any idea why this is the case?
You mock in this test the method queryForObject, but test on the method query.
I suppose that your code defines a mock of the function somwhere else, isn't it? It could then simply be the result of a copy/paste operation...
I also had the same problem. To solve that I replaced Mockito.anyList() (if param required is list) and Mockito.anyLong() (if param required is long). Example:-
Mockito.when(testService.getData(Mockito.anyLong(),
Mockito.anyList(), Mockito.anyList())).thenReturn(SOME_RESPONSE_DATA);

Converting Java object to JSONObject and transmit it at GET method.

I am working on an Android app, for which I am also working on a
Spring-MVC based server. Unfortunately before this, I have not done
that much work on JSONObjects. Currently, I am able to send Java
objects to the server from the Android app, and receive Java objects
too.
I am interested in using the Volley framework provided by Google,
which will avoid the hassle of Asynctask and is more efficient, but
it deals with JSONObject.
Unfortunately wherever I looked on the net, I found the code to
create JSOnObjects to save it in some file on Local Hard drive, but
no, I would like to transmit them in ResponseBody, can anyone help me
out with creating a JAVA object to JSOBObject and vice-versa. I have
all POM dependencies, and messageConvertors set in servlet-context.
Controller code current :
//Restaurant is just a plain Java class, I can give it as a JSONObject, but I dont know how to convert that JSONObject to java so I can save the restaurant in the server.
#RequestMapping(value = "/restaurant/add",method = RequestMethod.POST)
#ResponseBody
public String addRestaurantWebView(#RequestBody Restaurant restaurant){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
modelAndView.addObject(restaurant);
this.restaurantService.addRestaurant(restaurant);
return "true";
}
//Similarly, here, I don't know how to convert the Restaurant's list to JSONObject when there is a get Request.
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody List<Restaurant> listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
modelAndView.addObject("listRestaurant", restaurantList);
return restaurantList;
}
I hope my question was clear, if there is any doubt, please let me know. Thanks a lot.
Take a look at Google's Gson. It's a pretty concise API for converting objects to JSON. You can easily specify properties by adding the #Expose annotation in your classes to the properties you need to include. Try it like this:
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody String listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonString = gson.toJson(restaurantList);
return jsonString;
}
It's not necessary to annotate properties with #Expose but it will help if you end up having any circular references.
Good luck.

ActionLink doesn't work

I'm pretty sure that I'm doing something really stupid. Please have a look and let me know what I'm doing wrong.
Here is my ActionLink
#Html.ActionLink("Edit","Edit","UserProfile", new { id = Model.ApplicationUserId },null)
When I click this it throws the bad request exception and also I noticed the url is
https://localhost:44304/UserProfile/Edit/92b1347c-c9ec-4728-8dff-11bc9f935d0b
not
https://localhost:44304/UserProfile/Edit?userId=92b1347c-c9ec-4728-8dff-11bc9f935d0b
I have a HTTPGET Edit method in my controller and it takes UserId. When I pass the route values manually it works.Please help me.
Your help is much appreciated and someday, will pay it forward.
Thanks!
Cheers!
If the parameter you are expecting is userId, then use the #Html.ActionLink like this:
#Html.ActionLink("Edit","Edit","UserProfile", new { userId = Model.ApplicationUserId },null)
If you pass the parameter with name id, then the MVC will route like you mentioned:
https://localhost:44304/UserProfile/Edit/92b1347c-c9ec-4728-8dff-11bc9f935d0b
Which is great, but your method should be something expecting the parameter with the appropriate name:
// GET: /UserProfile/Edit/{id}
public ActionResult Edit(String id){
//your code
return View();
}
If you have some time, check out this ASP.NET MVC Routing Overview with a lot more details.
You need change parameter for your controller action Edit from userId to id - best variant.
public Edit(int id)
{
}
Or
#Html.ActionLink("Edit","Edit","UserProfile", new { userId = Model.ApplicationUserId },null)

Assign values to ssis variable

I am trying to assgin a value to a variable in script component using C# but unable to do so. Can anyone please post the code or tell me what wrong below.
public override void PostExecute()
base.PostExecute();
IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForWrite("User::Variable");
this.VariableDispenser.GetVariables(out varCollection);
varCollection["User::Variable"].Value = #"TESTING";
MessageBox.Show(Variables.MerchOrgName.ToString());
This example is very comprehensive. Most of the time the easier of the two methods is sufficient - especially if you are just starting.
http://microsoft-ssis.blogspot.com/2011/01/how-to-use-variables-in-script.html

create a StreamSource with getClass().getClassLoader().getResourceStream(

I post this question and I got some explanations but I couldn't solve the problem. Now since event I have a better understanding I'm going to post this again in a new angle.
I have following lines in my node.
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
/*
* Associate the schema factory with the resource resolver, which is
* responsible for resolving the imported XSD's
*/
factory.setResourceResolver(new ResourceResolver());
Source schemaFile = new StreamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
I think I have two options. Either to mock
Source schemaFile = new StreamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
or
Schema schema = factory.newSchema(schemaFile);
I have been pulling my hair for two day to do the first one. I tried as follows
expectNew(StreamSource.class, InputStream.class).andReturn(mockSource);
and
expectNew(StreamSource.class, anyObject(InputStream.class)).andReturn(mockSource);
But didn't work.
Now I'm trying to mock the second line
Schema schema = factory.newSchema(schemaFile);
This one also not quite clear to me. Do I need to mock a factory like
SchemaFactory mockFactory = EasyMock.createMock(SchemaFactory.class);
or since factory is created using newInstance static method call is it a different way?
Appreciate any help on this problem.
Adding later
I got some lead with the situation. I have expectNew as follows.
expectNew(StreamSource.class, InputStream.class).andReturn(mockStreamSource);
When I run powermocks throws a error saying.
java.lang.AssertionError:
Unexpected constructor call javax.xml.transform.stream.StreamSource(null):
javax.xml.transform.stream.StreamSource(class java.io.InputStream): expected: 1, actual: 0
The reason is as I think getClass().getClassLoader().getResourceStream("..") return null anyway. So powermock didn't find it euqal to the initialization I describe by expectNew. How to say expect a null inputstream as parameter. I tried using just null. didn't work.
expectNew(StreamSource.class, null).andReturn(mockStreamSource);
If you're using easymock:
Extract the creation of the factory to a protected method.
protected SchemaFactory createSchemaFactory(){
return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}
In your test, instead of test the SUT itself create a partially mocked version of your SUT, mocking only the new method where the static invocation is done, and test it. Partial mocks using easymock.