Have in integration test:
with mock.patch.object(
EmailMultiAlternatives, 'send', autospec=True,
side_effect=EmailMultiAlternatives.send
) as mocked_mail_send:
method_using_that_send()
mocked_mail_send # how to access here send's return value ?
Mocking purpose is to verify if my method will call external method, but I don't want mock entirely that send method and overwrite original return_value.
Found it as impossible to achieve in mock.
Resolved by splitting test to:
unit test with mocked send
integration test testing only result from that external send.
Related
Running spring boot 1.5.12 with Shiro starter 1.4.0
Trying to write up some unit tests to test a static class which checks permissions using the checkPermission of the Subject interface.
I'm mocking the shiro subject and stubbing the isPermitted method to return false for specific permission string... but for some reason, it passes when Subject.checkPermission is executed.
Subject subjectUnderTest = mock(Subject.class);
when(subjectUnderTest.isAuthenticated()).thenReturn(true);
when(subjectUnderTest.isPermitted(eq("review:edit:regional"))).thenReturn(false);
setSubject(subjectUnderTest);
subjectUnderTest.checkPermission("review:edit:regional");
I'm fairly new to Mockito but in this case was expecting AuthorizationException to be thrown by checkPermission given the isPermitted stub returning false.
If i change the implementation to use isPermitted, then test runs as expected..but current implementation is using checkPermission...
The method checkPermission() of the Subject interface will not call isPermitted() on itself but on the abstract AuthorizingRealm. The callchain for checkPermission() is like the following:
Subject.checkPermissions()->
DelegatingSubject.checkPermissions()->
Authoriser.checkPermission()->
AuthorizingRealm.checkPermission()->
AuthorizingRealm.isPermitted()
Therefore, mocking isPermitted() on the Subject will have no effect since checkPermission() will never call it on this object. To achieve the expected behavior, you have to mock the method on the AuthorizingRealm or alternatively on the AuthorizingSecurityManager incase calls to your SecurityManager are available under test.
We are implementing resource ownership and/or input validations through the use of FormRequest. Our controller tests are functional test so we don't mock Request but use the $this->call($method, $url, $params, ...).
The issue is that FormRequest is a subclass of Request. Is there a way to mock only the authorize() method but keeping the rest of the Request object non-mocked?
If so, how to? I already tried partial mocking with Mockery and it either didn't work or I did it wrong.
$this->mock(\Namespace\Http\Requests\CustomRequest::class . '[authorize]')
->shouldReceive('authorize')
-> .......
Use phpunit mocking system instead of Mockery.
$request = $this->getMock(\Namespace\http\Requests\CustomRequest::class, ['authorize']);
$request->expects($this->once())->method('authorize')->willReturn(true);
hope it helps;
Help me understand how to mock a service method inside a controller for unit testing in grails using JUnit
I was trying to write a unit test case for my controller "add".
void testAdd_UT_03(){
......declaring and assigning prerequisites
controller.add() // This is the controller i want to unit test
.... asserting
}
//Controller
def add{
def a =someService.method()
}
Inside controller, some service methods are getting called which in turn is using HQL statements. Since i could not find a way to deal with HQL statements in unit testing, i want to mock the service method itself. ( i want the service method to return the predefined output).
Could someone please explain how to achieve this?
Could you also explain when to use mockController? what we really achieve by mocking something? ( i dint get the real picture as i am entirely new to this)
Thanks in advance,
BK
you can add the following code in the setUp method of your test to mock the service method and when you call the method "add" method on your controller it will call the mocked service method.
def predifinedOutput
void setUp(){
def mockControl = mockFor(YourService)
//params are the parameters passed to the service method
mockControl.demand.yourServiceMethod(0..10) { params->
predifnedOutput = "predifinedOutput"
return "predefined output"
}
controller.yourService = mockControl.createMock()
}
I am new to writing test cases for WebAPI's. I have seen similar questions asked in the past, but not answered, but I am wondering how I would test my APIs if they have an ODataQueryOptions as part of the parameters. See below:
public IQueryable<Item> GetByIdAndLocale(ODataQueryOptions opts,
Guid actionuniqueid,
string actionsecondaryid)
Would I have to moq this? If so, how would this look? Any help would be appreciated.
For ODataQueryOptions perspective, you may want to test that all the OData query options can work with your Function. So firstly you need to create an instance of ODataQueryOptions. Here is an example:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
ODataQueryContext context = new ODataQueryContext(EdmCoreModel.Instance, elementType);
ODataQueryOptions options = new ODataQueryOptions(context, request);
So you need to create your own EDM model to replace EdmCoreModel.Instance, and replace requestUri with your query. elemntType in ODataQueryContext is "The CLR type of the element of the collection being queried".
I cannot tell from the phrasing, but is the above call (GetByIdAndLocale) the Web API that you are trying to test or are you trying to test something that is calling it?
One uses a mock or a stub to replace dependencies in a Unit Under Test (UUT). If you are testing GetByIdAndLocale() then you would not mock it though if it calls something else that takes the ODataQueryOptions as a parameter, you could use Moq to stub/mock that call.
If you are testing some unit that calls GetByIdAndLocale() then, yes, you could moq it. How exactly you might do this depends upon the goal (checking that the correct values are being passed in vs. checking that the returned IQueryable is correctly processed) basically, matching against It.IsAny() or against some matcher.
Which do you want to test?
GetByIdAndLocale(), something that calls it or something (not shown) that it calls?
What are you interested in verifying?
Correct options are passed in or the processing of the return from the mocked call?
I'm implementing a client consuming a webservice. I want to reduce dependencies and decided to mock the webservice.
I use mockito, it has the advantage vs. EasyMock to be able to mock classes, not just interfaces. But that's not the point.
In my test, I've got this code:
// Mock the required objects
Document mDocument = mock(Document.class);
Element mRootElement = mock(Element.class);
Element mGeonameElement = mock(Element.class);
Element mLatElement = mock(Element.class);
Element mLonElement = mock(Element.class);
// record their behavior
when(mDocument.getRootElement()).thenReturn(mRootElement);
when(mRootElement.getChild("geoname")).thenReturn(mGeonameElement);
when(mGeonameElement.getChild("lat")).thenReturn(mLatElement);
when(mGeonameElement.getChild("lon")).thenReturn(mLonElement);
// A_LOCATION_BEAN is a simple pojo for lat & lon, don't care about it!
when(mLatElement.getText()).thenReturn(
Float.toString(A_LOCATION_BEAN.getLat()));
when(mLonElement.getText()).thenReturn(
Float.toString(A_LOCATION_BEAN.getLon()));
// let it work!
GeoLocationFetcher geoLocationFetcher = GeoLocationFetcher
.getInstance();
LocationBean locationBean = geoLocationFetcher
.extractGeoLocationFromXml(mDocument);
// verify their behavior
verify(mDocument).getRootElement();
verify(mRootElement).getChild("geoname");
verify(mGeonameElement).getChild("lat");
verify(mGeonameElement).getChild("lon");
verify(mLatElement).getText();
verify(mLonElement).getText();
assertEquals(A_LOCATION_BEAN, locationBean);
What my code shows is that I "micro-test" the consuming object. It's like I would implement my productive code in my test. An example for the result xml is London on GeoNames.
In my opinion, it's far too granular.
But how can I mock a webservice without giving everystep? Should I let the mock object just return a XML file?
It's not about the code, but the approach.
I'm using JUnit 4.x and Mockito 1.7
I think the real problem here is that you have a singleton that calls and creates the web service so it is difficult to insert a mock one.
You may have to add (possibly package level) access to the singleton class. For example if the constructor looks something like
private GeoLocationFactory(WebService service) {
...
}
you can make the constructor package level and just create one with a mocked web service.
Alternatively you can set the webservice by adding a setter method, although I don't like mutable Singletons. Also in that case you have to remember to unset the webservice afterwards.
If the webservice is created in a method you might have to make the GeoLocationFactory extensible to substitute the mock service.
You may also look into remove the singleton itself. There are articles online and probably here on how to do that.
you really want to be mocking the results returned from the webservice to the code that will be using the result. In your example code above you seem to be mocking mDocument but you really want to pass in an instance of mDocument that has been returned from a mocked instance of your webservice and assert that the locationBean returned from the geoLocationFetcher matches the value of A_LOCATION_BEAN.
The easiest option would be to mock the WebService client,
when(geoLocationFetcher.extractGeoLocationFromXml(anyString()))
.thenReturn("<location/>");
You can modify the code to read the response xml from the file system.
Sample code can be found here: Mocking .NET WebServices with Mockito