i have a code like this
if (!executorService.awaitTermination(900000l,TimeUnit.MILLISECONDS)){
executorService.shutdowNow();
}
what i want is to mock the return type of awaitTermination to get false to go to the condition
what i did in test
#Mock
ExecutorService executorService;
Mockito.when(executorService.awaitTermination(anyLong(),any(TimeUnit.class)).thenReturn(false) // this line dont work it always return true when i debug it
any idea how to mock that line to get false ?
Related
I am writing an unit test in Spock and trying to stub RestTemplate.postForEntity() but seeing a weird issue where the stubs only works when I add a breakpoint and evaluate the expression. It doesnt work and calls the postForEntity() method when run normally.
Here is my implementation.
Test:
def "AuthTokenRequest"() {
given:
def url = "https://authEndpoint"
def map = new LinkedMultiValueMap<>()
RestTemplate restTemplate = GroovySpy(global: true)
restTemplate.postForEntity(*_) >> new ResponseEntity(new AuthResponse(), HttpStatus.OK)
when:
def responseEntity = client.authTokenRequest(url, map)
then:
responseEntity == response
}
Method making the HTTP request:
public AuthResponse authTokenRequest(String url, MultiValueMap map) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<AuthResponse> responseEntity = restTemplate.postForEntity(url, createAuthEntity(map), AuthResponse.class);
return responseEntity.getBody()?:null
}
When I run this test, I get a java.net.UnknownHostException exception because https://authEndpoint doesnt point anywhere which also proves that postEntity() is not being stubbed.
When I put a breakpoint on ResponseEntity<AuthResponse> responseEntity = restTemplate.postForEntity(url, createAuthEntity(map), AuthResponse.class); and evaluate the expression, I get the stubbed response.
Am I doing this wrong?
I am currently trying to use spock instead of junit in my unit tests.
But I ran into problem of MissingMethodInvocationException.
I am mocking Provider<T>.get(), like below
Provider<SomeOjb> a = Mock()
def setup(){
SomeOjb obj = new SomeObj();
Mockito.when(a.get()).thenReturn(obj)
}
but after running it I am getting
org.mockito.exceptions.misusing.MissingMethodInvocationException
when() requires as argument which has to be 'a method call on a mock'
I tried two diffrent approach, one of them is to create mock as
def a = Mock(Provider<SomeObj>) but in this case I getting syntax error after running, issue is with <>
And the last idea was to just use annotation
#Mock
Provider<SomeObj> a;
and use when/then as before, and in this case it worked alright.
Any idea why firt idea is not correct?
Obviously I am stupid.
Issue was because I used Mockito api. Not spock mock api.
It should looks like:
Provider<SomeOjb> a = Mock()
def setup(){
SomeOjb obj = new SomeObj();
a.get() >> obj
}
I'm pretty new to phpunit and mocking, and I want to test a Listener in my symfony2 project, what is a kernel exception listener.
This is the class I want to test:
public function onKernelException(GetResponseForExceptionEvent $event)
{
$code = $event->getException()->getCode();
if($code == 403)
{
$request = $event->getRequest();
$session = $request->getSession();
$session->getFlashBag()->add('notice', 'message');
$session->set('hardRedirect', $request->getUri());
}
}
And first I just wanted to test, so nothing happens if the code is 404, this is the test I wrote:
public function testWrongStatusCode()
{
$exceptionMock = $this->getMock('Exception')
->expects($this->once())
->method('getCode')
->will($this->returnValue('404'));
$eventMock = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent')
->disableOriginalConstructor()
->getMock();
$eventMock->expects($this->once())
->method('getException')
->will($this->returnValue($exceptionMock));
//here call the listener
}
but PHPunit say, getCode function was never called.
You can't use "chaining" as you've tried. The reason is that methods getMock and will return different objects. That's why you lose your real mock object. Try this instead:
$exceptionMock = $this->getMock('\Exception');
$exceptionMock->expects($this->once())
->method('getCode')
->will($this->returnValue('404'));
Edit
Ok. The problem is you cannot mock getCode method because it's final and it's impossible to mock final and private methods with PHPUnit.
My suggestion is: just prepare an exception object you want, and pass it as returned value to event mock:
$exception = new \Exception("", 404);
(...)
$eventMock->expects($this->once())
->method('getException')
->will($this->returnValue($exception));
This is how I mock the getCode() function. It actually gets called from the ResponseInterface::getStatusCode() function, so that is what you need to mock:
$guzzle->shouldReceive('get')
->once()
->with(
$url
)
->andThrows(new ClientException(
"",
Mockery::mock(RequestInterface::class),
Mockery::mock(ResponseInterface::class, [
'getStatusCode' => 404,
]),
));
You can use mockery library with PHPUnit, which is great tool and makes life easier.
$exceptionMock = \Mockery::mock('GetResponseForExceptionEvent');
$exceptionMock->shouldReceive('getException->getCode')->andReturn('404');
Check out documentation for more... and I hope you will love it.
I've got a service, which is using sendJMSMessage method which is provided by jms-grails plugin.
I want to write some unit tests, but I'm not sure how to "mock" this method, so it just does nothing at all.
Any tips?
You can metaClass the method to have it return whatever you want.
#Test
void pluginCode() {
def myService = new MyService()
def wasCalled = false
myService.metaClass.sendJMSMessage = {String message ->
//I like to have an assert in here to test what's being passed in so I can ensure wiring is correct
wasCalled = true
null //this is what the method will now return
}
def results = myService.myServiceMethodThatCallsPlugin()
assert wasCalled
}
I like to have a wasCalled flag when I'm returning null from a metaClassed method because I don't particularly like asserting that the response is null because it doesn't really assure that you're wired up correctly. If you're returning something kind of unique though you can do without the wasCalled flag.
In the above example I used 1 String parameter but you can metaClass out any number/type of parameters to match what actually happens.
I am currently trying to go back through and write unit tests for some code that wraps an existing class. The function I am looking for has code that looks like the following...
private OldObject oldObject
...
public Boolean method(){
Boolean returnValue = false
if(oldObject.method(100)){
returnValue = true
}
if(oldObject.method(101)){
returnValue = true
}
}
I have thought about using metaClass, something like OldObject.metaClass.method{return true} but I'm not sure how to remove this before the next tests.
Anyone have best practices/help for this kind of situation?
To mock the method use:
OldObject.metaClass.method = {return true}
Be aware that this will mock the method for all instances of OldObject, but it's also possible to mock the method just for a single instance. When you want to remove the mocked method just set the metaClass to null:
OldObject.metaClass = null
I think you need to be using at least Groovy 1.6 for this to work.