How to wrap (envelop, enclose?) #WebMethod execution in custom annotated class - web-services

With using of JAX-WS, implemented #WebMethod method in #WebService class.
Need to do something like this:
WebService.java:
#WebMethod
#MyWrapper
public Object someWebserviceMethod() ...
Here is MyWrapper annotation, which must wrap call of someWebserviceMethod into another code, where it will be decided whether to execute it or not. For example, in such way:
MyWrapperImpl.java:
...
public Object wrapMethodExecution( contextOfCalledWebMethod ) {
if ( someFlag ) {
//then contextOfCalledWebMethod called to execute someWebserviceMethod
//or directly call Method.invoke()
} else {
return null; //or error message
}
So wrapMethodExecution() needs to be automatically called before the call to any method, annotated with #MyWrapper.
Is it possible to perform such pattern by using jax-ws?
I tried to use WebServiceFeatureAnnotation but failed.

Related

Mockery not executing mock method

I have class Name Validator and it has a method forVote.
This is my code.
public function test_should_set_default()
{
$this->mock = \Mockery::mock(Validator::class);
$this->mock->shouldReceive('forVote')
->andReturnTrue();
$this->app->instance(Validator::class,$this->mock);
$factory = new Factory();
$this->assertTrue($factory->setDefault());
}
So Factory calls Processor which calls Validator. Now I want mock validator to run. But it calls the real method.
What am I doing wrong?
https://laravel.com/docs/5.6/container#introduction
since the repository is injected, we are able to easily swap it out
with another implementation. We are also able to easily "mock", or
create a dummy implementation of the UserRepository when testing our
application.
My guess is you are perhaps currently instantiating your dependencies like so:
$processor = new Processor() and $validator = Validator::make(...);
So, in order to have your mocked class be used, you should use Dependency injection which just means your classes should inject your dependencies via the __construct method.
Your Factory class should be like:
class Factory {
$processor;
public function __construct(Processor $processor)
{
$this->processor = $processor;
}
public function setDefault()
{
$this->processor->callingValidator();
}
}
and your Processor to be like:
class Processor {
$validator;
/**
* The Validator will resolve to your mocked class.
*
*/
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
public function callingValidator()
{
$this->validator->make();
}
}

Mockito - how to mock/verify a method call which accepts a new object?

I have a method (method1) that I'd like to test, which based on parameters provided creates an object and calls another method (method2). So I'm mocking method2, which accepts an object (sampleObj).
public void method1(booleanParam) {
if(booleanParam){
List<SampleObj> fooList = new ArrayList<SampleObj>;
fooList.add(new SampleObj("another param"));
anotherService.method2(fooList);
}
//some other smart logic here
}
And here's my test with same obfuscated names (sorry if I missed any typo):
public void testMethod1() {
AnotherService mockedAnotherService = PowerMockito.mock(AnotherService.class);
ServicesFactory.getInstance().setMock(AnotherService.class, mockedAnotherService);
List<SampleObj> fooList = new ArrayList<SampleObj>;
fooList.add(new SampleObj("another param"));
// assert and verify
service.method1(true);
Mockito.verify(mockedAnotherService, times(1)).method2(fooList);
}
The problem is, when I try to mock the anotherService, I need to pass an object to method2, so I have to create a new one. But since it's a new object, it's not the same object, which will be passed from inside the method1, hence the test fails with the exception:
Argument(s) are different! Wanted:
anotherService.method2(
[com.smart.company.SampleObj#19c59e46]
);
-> at <test filename and line # here>
Actual invocation has different arguments:
anotherService.method2(
[com.smart.company.SampleObj#7d1a12e1]
);
-> at <service filename and line # here>
Any ideas how to accomplish that?
You have a few options:
Implement equals and hashCode on SampleObj. Because you didn't wrap fooList in a matcher, Mockito checks with List.equals, which checks equals for corresponding objects in each List. The default behavior of Object.equals is that a.equals(b) iff a == b--that is, objects are equal iff they refer to the same instance--but you're welcome to override that if every SampleObj("foobar") equals every other SampleObj("foobar").
Use a Hamcrest Matcher you write.
private static Matcher<List<SampleObj>> isAListWithObjs(String... strings) {
return new AbstractMatcher<List<SampleObj>>() {
#Override public boolean matches(Object object) {
// return true if object is a list of SampleObj corresponding to strings
}
};
}
// in your test
verify(mockedAnotherService).method2(argThat(isAnObjListWith("another param")));
Note that you could also just make a Matcher of a single SampleObj, and then use a Hamcrest wrapper like hasItem. See more matchers here.
Use a Captor to check equals your own way:
public class YourTest {
// Populated with MockitoAnnotations.initMocks(this).
// You can also use ArgumentCaptor.forClass(...), but with generics trouble.
#Captor ArgumentCaptor<List<SampleObj>> sampleObjListCaptor;
#Test public void testMethod1() {
// ...
verify(mockedAnotherService).method2(sampleObjListCaptor.capture());
List<SampleObj> sampleObjList = sampleObjListCaptor.getValue();
assertEquals(1, sampleObjList.size());
assertEquals("another param", sampleObjList.get(0).getTitle());
}

PHPUnit Mock overrides existing methods

I'm writing a unit test for a REST Service connector which is using a third party tool called Httpful.
Because I do not want to send real requests to the server, I mocked the "send" method from Httpful\Request:
$mockedRequest = $this->getMock('Httpful\Request', array('send'), array(), '', false);
$mockedRequest->expects($this->once())->method('send');
This works fine, but the Request Class has a method called expects itself, which I use in my actual code to define the acceptable mime type of the response.
$this
->getRequest('GET')
->uri(ENDPOINT . $configurationId) //by default this returns a Request Object (now mocked request)
->expects('application/json') //crashes ...
->send();
When the code gets executed, I get the following error (which is understandable):
Argument 1 passed to Mock_Request_938fb981::expects() must implement interface PHPUnit_Framework_MockObject_Matcher_Invocation, string given
Is there something like a configurable prefix for methods coming from the Mock Class like "expects"?
I don't think that you will be able to do that using the PHPUnit_MockObject class. But you can code your own and use that instead.
class MockRequest extends \Httpful\Request {
public $isSendCalled = false;
public $isUriCalled = false;
public $isExpectsCalled = false;
public function uri($url) {
if($url !== '<expected uri>') {
throw new PHPUnit_Framework_AssertionFailedError($url . " is not correct");
}
$this->isUriCalled = true;
return $this;
}
public function expects($type) {
if($type !== 'application/json') {
throw new PHPUnit_Framework_AssertionFailedError($type . " is not correct");
}
$this->isExpectsCalled = true;
return $this;
}
public function send() {
$this->isSendCalled = true;
}
}
Your line for creating the mock then just becomes:
$mockedRequest = new MockRequest();
If the constructor fo
Then in your test you can verify that the methods are called with
$this->assertTrue($mockedRequest->isSendCalled);
$this->assertTrue($mockedRequest->isUriCalled);
$this->assertTrue($mockedRequest->isExpectsCalled);
This isn't a very dynamic mock but it will pass the type hinting and does your check for you. I would create this mock in the same file as your test (though be careful about not accidentally redefining this class elsewhere in your test suite). But it gets you around the problem of having expects being overridden.
The PHPUnit_Framework_MockObject_MockObject is an interface that sets the signature for expects() also which your class wouldn't meet and so there would be an error if you were able to rename the method.
https://github.com/sebastianbergmann/phpunit-mock-objects/blob/master/src/Framework/MockObject/MockObject.php

call parent function of mocked class

I have got the following question.
class A
{
public function isNew()
{
return ($this->ID == 0);
}
}
class B extends A
{
//Some functions
}
Now I want to mock Class B. So I have got some statements
$oMockedStm = $this->getMockBuilder('B')->getMock();
$oMockedStm->expects($this->any())->method('someMethod')->will($this->returnValue(TRUE));
$oMockedStm->expects($this->any())->method('anotherMethod')->will($this->returnValue(TRUE));
Now When I do
$this->assertTrue($oMockedStm->isNew());
I get the Error: Failed asserting that null is true.
How can this be. The function always returns true of false.
Does it have something to do with the fact that you can't call parent method of mocked objects?
I figured out that I didn't want to mock the whole class. Only specific functions.
So what you so when defining your mock object is you use the setMethods() function to specify the specific functions you want to mock.
So like this:
$oMockedStm = $this->getMockBuilder('B')
->setMethods(array('someMethod','anotherMethod'))
->getMock();

Mock/Test Super class call in subclass..is it possible?

I am looking for a solution to mock the super call in subclass ButtonClicker.
Class Click {
public void buttonClick() throws java.lang.Exception { /* compiled code */ } }
Class ButtonClicker extends Click {
#Override
public void buttonClick() throws Exception {
super.buttonClick();
} }
Using inheritance reduces testability of your code. Consider replacing inheritance with the delegation and mock the delegate.
Extract the interface IClicker
interface IClicker {
void buttonClick();
}
Implement IClicker in Clicker class. In case that you are working with third-party code consider using Adapter Pattern
Rewrite your ButtonClicker as following:
class ButtonClicker implements IClicker {
Clicker delegate;
ButtonClicker(Clicker delegate) {
this.delegate = delegate;
}
#Override
public void buttonClick() throws Exception {
delegate.buttonClick();
}
}
Now just pass the mock as a constructor parameter:
Clicker mock = Mockito.mock(Clicker.class);
// stubbing here
ButtonClicker buttonClicker = new ButtonClicker(mock);
The answer is no. A mock is only a trivial interface implementation. (I mean interface in the API sense, not the specific Java keyword sense.) So it doesn't know about any implementation details like which class actually implements the functionality (there is no functionality, essentially).
You can create a 'spy' on a real object that will let you mock only some methods and not others, but that also will not let you mock just the super method of a class because the method(s) you choose to mock are typically chosen by the signature, which is the same for both the sub class and the super class.