How to mockup TWebRequest/TIdHTTPAppRequest? - unit-testing

I have a function that accept a TWebRequest by argument, eg.:
function foo(const request: TWebRequest ): boolean;
how can i create a TWebRequest and set some property like:
Host
ServerPort
QueryFields
ContentFields
I have tried:
var
aWebRequest: TWebRequest;
begin
aWebRequest := TWebRequest.Create;
but on creation Delphi raise an exception:
First chance exception at $XXXXXXXX. Exception class EAbstractError
with message 'Abstract Error'.
the descendant is TIdHTTPAppRequest, but it require:
constructor TIdHTTPAppRequest.Create(
AThread: TIdContext;
ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo
);
each argument require other object etc etc.
there is a simple way (eg. third party unit, unknown snippet or trick) for mockup a request for unit test purpose?

EAbstractError usually means that you are trying to instantiate generic abstract class (e.g. TStrings) instead of it's descendant that contains required implementations (e.g. TStringList). So you need to find the TWebRequest descendant and use it instead.
For mocking purposes you could try to write your own "empty" descendant, but I doubt that will work as expected.

Related

Observing test failure messages

I am using boost test within a home-grown GUI, and want to access test results (e.g. the failure message and location when a test fails)
The unit_test::test_observer class provides the virtual method:
void assertion_result(boost::unit_test::assertion_result)
However, unit_test::assertion_result is just an enum indicating success or failure. From there, I cannot see how to access further information about the test result.
The framework also provides the class test_tools::assertion_result, which encapsulates an error message, but this only appears to be used for evaluating pre-conditions. (I would have expected this type to be the argument to unit_test::test_observer::assertion_result).
The log output classes appear to provide more information on test results. These are implemented as streams, which makes it non-trivial to extract test result data.
Does anyone know how I can access the information on test results - success/failure, the test code, the location, etc?
Adding an observer will not give you the level of details you need.
From this class you can add your own formatter using the add_formatter function. This will contain the details of what is happening and where, depending on the formatter log level.

liferay 7 jsonws API dlfileentry obc parameter example

I wanto to try the web service of dflservice entry into the web service portal
http://localhost:8080/api/jsonws
but the parameter used obc just explain as obc with the type com.liferay.portal.kernel.util.OrderByComparator, I try null, 0, +obc:com.liferay.portlet.documentlibrary.util.comparator.FolderNameComparator, but always have the same result:
Conversion failed: com.liferay.portal.kernel.util.OrderByComparator
What is the correct parameter
According to documentation:
You can't pass 0, as obc is an object type parameter.
To pass a null value for obc, you need to prefix it with a dash like: /-obc.
And to pass an instance of an object parameter, you need to prefix the parameter with a plus sign like: /+obc:com.liferay.portlet.documentlibrary.util.comparator.FolderNameComparator (Should work as well).
As com.liferay.portal.kernel.util.OrderByComparator is an abstract class, you need to pass a concrete implementation. Check the implementation of DLImpl.getRepositoryModelOrderByComparator method for further concrete implementations of OrderByComparator class for document library.
Also, I would like you to share the URI(s), you are trying. So, I can also try them.
Reference:
INVOKING JSON WEB SERVICES
Update:
There is bug in JSONWS GUI, which is already fixed in:
https://issues.liferay.com/browse/LPS-76955?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel
However, the URL access is working for me:
http://localhost:8080/api/jsonws/dlfileentry/get-file-entries/group-id/10184/folder-id/0/status/0/start/-1/end/-1/+obc:com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelNameComparator
Here, com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelNameComparator is a concrete implementation of obc.

ActionListener Expression value for RichButton in ADF

We have a business need to collect specific bindings in every JSF page. and we do that inside overridden ViewHandlerWrapper class
I use the below code inside renderView method to get the whole expression value property for every RichInputText and it's work fine for me
ValueExpression valExp = Inputcomponent.getValueExpression("value");
String ExpressionString = valExp.getExpressionString();
output was: #{binding.EmployeeId.inputValue}
When I do the same against RichButtin I got null value as following:
ValueExpression valExp = Btncomponent.getValueExpression("actionlistener");
String ExpressionString = valExp.getExpressionString();
What is the wrong in my last peace of code?
Obtaining a ValueExpression form a RichInputText works because, as the name suggests, it evaluates to a value, which may or may not be an EL expression, let alone a method.
On the other hand, a RichButton does not really have to evaluate to something; rather, it aims to invoke behavior (i.e. a method), from which you would want a MethodExpression - though in this case, the closest we get to it is a MethodBinding.
Luckily, UIXCommand, a superclass of RichButton, provides two methods from which you can obtain your action listeners:
public final MethodBinding getActionListener()
From the MethodBinding returned, you can invoke getExpressionString() so you can get what you wanted - such as some actionListener EL string like #{binding.bean.actionListenerMethod}.
public final ActionListener[] getActionListeners()
Might be worth mentioning, though there is not much merit for this in your use case. It simply returns the listeners on which you can manually process the events.

getting InvalidUseOfMatchersException in a proper use of matchers

Everything sounds correct but I get org.mockito.exceptions.misusing.InvalidUseOfMatchersException, when I try to mock a protected method.How Can I solve it ?
private Service service;
private System system;
#BeforeMethod
public void setupMocks() throws Exception {
service = powerMock.mock(Service.class);
system = powerMock.mock(System.class);
}
public void sample_Test() {
PowerMockito.doReturn(system).when(service, "getValidatedDto",
Matchers.any(Long.class), Matchers.any(Date.class));
// some code
}
I suspect you are seeing this exception:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 2 recorded:
With this additional context:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
If so, then this is because you are mixing parameters in the form of matchers (Matchers.any(Long.class), Matchers.any(Date.class)) with parameters in the form of raw values (service, "getValidatedDto").
The signature of the method under test is unclear to me but I think it might be something like
System getValidatedDto(Long aLong, Date aDate);
If so, then the correct invocation would be:
PowerMockito.doReturn(system).when(service).getValidatedDto(
Matchers.any(Long.class), Matchers.any(Date.class));

Mockito - Invalid use of argument matchers

I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.
my publisher method the uses the jmsTemplate to send method looks like following inside..
jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
return obj;
}
});
in My tests..
JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate,
Mockito.times(1)).send("appointment.queue",
Mockito.any(MessageCreator.class));
But when in the execution i get
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
....
Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.
Update
And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well
I think the rest of the message tells you what the problem is. When you use an argument matcher for one of the arguments, all the other arguments must also use an argument matcher:
Mockito.verify(mockTemplate, Mockito.times(1)).send(
Mockito.eq("appointment.queue"),
Mockito.any(MessageCreator.class));
For future readers. This will save you a lot of time.
We cannot use argument matcher and primitive/raw values together.
when(fooService.getResult("string",any(MyClass.class))).thenReturn(1); // will give error
when(fooService.getResult(anyString(),any(MyClass.class))).thenReturn(1); // correct
I think you cannot use argument matchers outside stubbing. I also got the same error but when I return, I had to do new string() instead of Mockito.anyString() and the error goes away.
Example:
Mockito.when(mockedBean.mockedMethod(Mockito.anyString(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyBoolean())).thenReturn(new String());
I can see that this question is about Java code, but I will share this because we use Mockito in Scala as well.
I had this exception thrown from the following code that mocks Play.api configurations
"Configurations Service" should {
"return all dataset configurations" in {
val configs = mock[Configuration]
val testData = Seq("SOME VALUE")
val loader = any[ConfigLoader[Seq[String]]]
when(configs.get[Seq[String]](any[String])).thenReturn(testData) // EXCEPTIONN HERE !
val configuration: ConfigurationsService = new ConfigurationsService(configs)
assert(configuration.getSupportedDatasets() == testData)
}
}
In Scala methods can have Implicit parameters configs.get method has one explicit param and an Implicit one I passed a mock object and when an exception was thrown I was wondering what is going on as I didn't MIX params and mocks, it turned out that I had to pass mocks to implicit parameters as well, and this solved the problem.
val loader = any[ConfigLoader[Seq[String]]] // configs.get has one implicit parameter that accepts ConfigLoader[Seq[String]]
when(configs.get[Seq[String]](any[String])(loader)).thenReturn(testData)
I was seeing this error about a mismatched # of arguments, despite having the correct number...
I realized this was because method being stubbed was static. When I converted it to non-static, it worked as expected.