w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Rspec to mock my call to external api from my function and return custom response back to the function
Checkout https://github.com/bblimke/webmock or http://fakeweb.rubyforge.org/ Then you do something like: stub_request( :post, "#{GITHUB_URL}1.json" ).to_return( body: { actor_attributes: {name: "Bill"} }.to_json ) I'm a bigger fan of Webmock than Fakeweb (it's got a few more features), but they'll both do for you, and it's pretty easy to switch between them.

Categories : Ruby On Rails

Mock static method Activator.CreateInstance to return a mock of another class
Well, I am tempted to say that this is not something you need to mock as it should be trusted to be under test, but I guess if the type is from an external source library, then you might have problems...that being said, the only way you can achieve this is to wrap Activator so that it is not a static class. Something like this: public ActivatorWrapper { public virtual object CreateInstance(Type type) { return Activator.CreateInstance(type); } }

Categories : C#

Python mock library: Is there any way to get corresponding return values from magic mock calls?
You don't need a side_effect, that is what mocks do already without it, they return other mocks. You make assertions on them by doing mymock.return_value.assert_called_once_with(4) If you did though, you'd just return a mock you had a reference to elsewhere from side_effect.

Categories : Python

How to mock a method call in Rspec
Firstly, you want to use any_instance: YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"]) Currently, you are checking if the class method refresh_auth_token is being called. It isn't, as it doesn't exist. Next, as the code is executed in the constructor, that line won't catch the call, as the object is already created in the subject line before the spec. This is the easiest solution: context "when token is nil" do it "refreshed the authentation token" do YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"]) YouTube.new(data["uid"], nil, data["refresh"]) end end

Categories : Ruby

Using mock to mock an imported module for testing a Pylons controller function
A controller could not be used as an independent object without an initialized Pylons' environment. Using the functionality Pylons provides for testing saves you from all the boilerplate code to test a Controller. I recommend you to use the TestController class in combination with nosetests as shown in documentation. Specifically for your code, I think Pylons treats private methods (starting with _) differently from public methods because public methods run in the context of a request.

Categories : Python

Mock Models and Stubbing for RSpec Controller Tests
You can't use both Viewing.any_instance.stub(:save) and viewing.should_receive(:save) The first one is use for control flow, whereas the second one is used to test something. You should do: let!(:viewing) { Viewing.new } # no lazy load, executed right away, no need to mock def action post :create, office_listing_id: office_listing.id end before do Viewing.stub(:new).and_return(viewing) end it "calls save" do expect(viewing).to receive(:save).and_return(true) action end

Categories : Ruby On Rails

How to mock a hash with string keys in rspec which comes from a webservice in the new hash notation of ruby
If the hash is a string key, you're not able to use the new notation. Only with symbols. In the case that you'd really like to access using symbols, one option is to import Rails ActiveSupport and use their Indifferent Access functions. It adds another dependency to manage, but can help keep your code cleaner too.

Categories : Ruby

Bypass php is_numeric() function is possible?
Why would you even use mysql library, when it is deprecated? Use mysqli instead. Secondly, if you want to get rid of any danger of sql injection, it would be much easier to use prepared statement, so something like the following is all that is needed. $stmt = $mysqli->prepare("SELECT first_name, last_name FROM users WHERE user_id = ?") $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($res); $stmt->fetch(); if($res) ... By the way, mysqli can be used in functional (not oop) style very similar to mysql.

Categories : PHP

Bypass function "out" parameters
You can create a wrapper: procedure test(); overload; var SomeVar : string; begin test(SomeVar); end; Note: You'll also have to mark the other version with overload, or you can call your wrapper something other than test, and remove the overload. Another option: declare a dummy variable somewhere (at the top of your unit, maybe): var DummyStr : string; Then you don't have to declare a new variable every time you want to call the function. test(DummyStr);

Categories : Delphi

python mock.mock_reset() returns mock instead of resetting the mock
Found the issue. Due to some convoluted way of mock creation, I was calling patch() on an already patched module, namely, I was patching a Mock() object. Since autospec was True for the patch call, mock_reset() was patched. The solution was to simplify mock creation flow.

Categories : Python

How to bypass the exif_imagetype function to upload php code?
For security i use $extension = pathinfo(strtolower($_FILES['upload']['name']), PATHINFO_EXTENSION); if(!in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) { echo "File is not an image"; }

Categories : PHP

Return a Value when using Mock repository
You don't need a Mock at all, you should be testing the implementation directly: PremiumResponse response = new PremiumResponse(); Assert.AreEqual(4, response.MultiplyValues(2, 2)); You would use a mock of an interface when you are testing a different section of code that depends on that interface. The purpose would be to have predictable return values so that you can properly formulate your expectations, and to prevent any potential bugs in one area of your code from affecting the unit test results for another. For example, say you had another class, Foo: public class Foo { private IPremiumResponse _premiumResponse; public Foo(IPremiumResponse premiumResponse) { _premiumResponse = premiumResponse; } public int DoSomeMathThenAddOne(int n) {

Categories : C#

Have function return request data + a function to execute
How about Edit xmlhttp.onreadystatechange = (function(xmlhttp, url, somevar1, somevar2){ return function() { cfunc.call(this, xmlhttp, url, somevar1, somevar2); } })(xmlhttp, url, somevar1, somevar2);

Categories : Javascript

Rspec don't recognise any method of RSpec::Matcher and RSpec::Core
You have three ls in your ReservationsControlller class name, which is why Rails is not finding the expected controller class when it loads the controller file. As for the rspec problem, perhaps you're missing an enclosing describe, but please share your spec so that we can see what's going on. Update: Looking at your spec, you've set your subject to @reservation, but haven't initialized @reservation, so it's value will be nil. Also, since you used the class Reservation as the argument to the outer describe, the subject would implicitly be Reservation.new without the subject call. As for the errors you're now getting, I'm not sure. of_type seems to be defined in mongoid-rspec, which you haven't explicitly included, but you're not getting an error from have_fields, which I thought was def

Categories : Ruby On Rails

Modify return property value of mock object
Moq will leave all methods unimplemented unless instructed to do otherwise, and that includes properties. If you use mockDocument.SetupProperty(doc => doc.DocumentName); it will implement the property as a regular auto-property. You can use mockDocument.SetupAllProperties() if you want all properties to be auto-implemented, but you'll still have to do it for every mock object. You could also consider making a stub instead of a mock: public class StubDocument : IDocument { public string DocumentNo { get; set; } public string DocumentName { get; set; } ... } In general, I find that stubbing is often preferable to mocking when dealing with very simple interfaces, as seems to be the case with your IDocument.

Categories : C#

How to mock malloc to return null in GMOCK?
DeveloperLove, first of all mocking of standard library is never a good practice and testing the code on such granulation level is art for art's sake. You have to notice that from very beginning, tests become the part of the project and if you want to keep them up-to-date (aka maintaing working regression) you have to think about their design in the same way as production code. In fact tests are also the code which has to be maintained during lifetime of project and if reading, correcting and finnaly understading that tests will take too much time, such regression will be useless. Try to think about it as the "life documentation". Nevertheless, probably one of the ugliest way to mock the standard C library is static hook and macros. Consider the following example: #include <gtest/gte

Categories : C++

Use PowerMock to mock methods chain with return value
Yes its possible . i have created a sample code for you using PowerMockito. create a singleton class .. public class SingletonClassUtil { private static SingletonClassUtil singletonClassUtil; private SingletonClassUtil(){} private String name; public static SingletonClassUtil getInstance() { if(singletonClassUtil!=null) { singletonClassUtil = new SingletonClassUtil(); } return singletonClassUtil; } public String getA() { return name; } } now test the class using PowerMock .. public class SingletonTest { public void testSingleton() throws Exception { PowerMockito.suppress(PowerMockito.constructor(SingletonClassUtil.class)); PowerMockito.mockStatic(SingletonClassUtil.class); Singleton

Categories : Testing

Rspec won't let me set return value for "any?" method with stubs or should_receive
The problem is, that each time you call the collect method, a new object is created, so stubbing one result of collect does nothing to the object that is return by the next call of that method. You should use stub_chain instead (stubbing the method chain on your ActiveRecord object). Note that you should work with the same ActiveRecord object that your controller retrieves, one possibility to ensure this is to stub the corresponding query call made by your controller action. Another possibility would be stubbing the method chain on any_instance of the ActiveRecord class.

Categories : Ruby On Rails

How to mock a method to return a string appended with its argument(java) using powermock
Even though you should be injecting in a separate class to do the table name generation, you can use Mockito's spy functionality. It looks like your code won't compile but, in your test do something like this: public class ExampleTest() { private abc example = new abc(); @Test public void test() { abc spy1 = spy(abc); stub(spy1. getTable("table1")).toReturn("ABC"); stub(spy1. getTable("table2")).toReturn("ABC") // do some testing on example... } } You would have to import the Mockito static stub and spy methods.

Categories : Java

Mock a method call with void return type using JMockit or Mockito
I was not sure what the Holder interface looked like so I made some assumptions. But, this is how you mock a method with a void return type using Mockito: @SuppressWarnings("unchecked") @Test public final void test() { // given final String expectedStatus = "status"; final String expectedMessage = "message"; final MyPort mockPort = mock(MyPort.class); final Answer<Void> registerAnswer = new Answer<Void>() { // actual parameter type doesn't matter because it's a void method public Void answer(final InvocationOnMock invocation) throws Throwable { // Here I'm stubbing out the behaviour of registerService final Object[] arguments = invocation.getArguments(); // I don't actually care about these, but if you wanted the

Categories : Unit Testing

Is there any method to bypass canvas security exception (external image to data string)
Nope you have to apply CORS headers to the server response hosting the images for this to work if it is cross domain. This does not have universal browser support either. Many Native Mobile browsers don't support it unfortunately.

Categories : Javascript

LINQ FUNCTION TO RETURN LIST BUT COMPILER SAYS function doesn't return a value on all code path
All code paths don't return a value. If searchtype = "withdatetime" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Convert.ToDateTime(startdate) And locations.DATE_COMTD <= Convert.ToDateTime(enddate)) _ And (locations.gettimecom >= starttime And locations.gettimecom <= endtime) _ Select locations Return giveloc.ToList ElseIf searchtype = "withdate" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Conv

Categories : Asp Net

What's wrong with my AES encryption function in C#? Why does it return zero length data?
You need using blocks around your streams to ensure they are closed and flushed. Try this: public static byte[] AES_Encrypt(byte[] data, string[] aes_key) { var aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 256; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.Default.GetBytes(aes_key[0]); aes.IV = Encoding.Default.GetBytes(aes_key[1]); var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); using(MemoryStream ms = new MemoryStream()) { using(CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) cs.Write(data, 0, data.Length); return ms.ToArray(); } } public static byte[] AES_Decrypt(byte[] data, string[] aes_key) { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256;

Categories : C#

PostgreSQL return a function with a Custom Data Type
This should just work. The enum should not be a problem. Tested with Postgres 9.1 and 9.2 CREATE TYPE building_code AS ENUM ('IT','EMS','HSB','ENG'); CREATE TEMP TABLE venue (id int PRIMARY KEY, building_code building_code); INSERT INTO venue VALUES (1, 'ENG'); CREATE OR REPLACE FUNCTION room_code(_id int) --! RETURNS building_code AS $func$ SELECT building_code FROM venue v WHERE v.id = $1 -- ! $func$ LANGUAGE SQL; SELECT * FROM room_code(1); Except ... In versions before 9.2 you can only use positional (numeric) parameters ($1) in SQL functions (unlike plpgsql functions). In 9.2+ the column name would take precedence, so that the WHERE clause of your original code would always be TRUE and all rows would qualify - except that your function only returns the first, since it does n

Categories : SQL

how do I return data from a node.js request call? (undefined is not a function)
callback seems to be undefined because you didn't pass it to your modules method should be like this: tools.getServerPermalink(checkSession.username, function(argument, newPermalink){ res.redirect('/'+ newPermalink) ; }); Also tools.getServerPermalink()doesn't directly return the url (it does not return anything, as the internal request is asynchronous) but passes it as the second argument to your callback function.

Categories : Node Js

Python mock library not returning correct mock object for 'patch'
import logging from mock import Mock, patch my_mock = Mock() my_mock.id = 'i-12341234' with patch('logging.PlaceHolder', new=my_mock) as mockobj: mockobj.return_value = mockobj # <-- added this line. print mockobj.id newobj = logging.PlaceHolder(None) print newobj.id Alternative import logging from mock import Mock, patch my_mock = Mock() my_mock.id = 'i-12341234' my_mock.return_value = my_mock # <--- with patch('logging.PlaceHolder', new=my_mock) as mockobj: assert mockobj.id == 'i-12341234' newobj = logging.PlaceHolder(None) assert newobj.id == 'i-12341234'

Categories : Python

How to return array from JavaScript function that retrieves data from text file?
Your DefineUserData function is returning a Promise, not a value. Additionally done functions don't return anything. Instead you'll need to use then functions instead of done functions in DefineUserData and then handle add a done function (or then) to the code that calls this function. Also, You can make your promises easier to read, and easier to work with by chaining then functions instead of nesting them. Currently on Win7 at the office so I can't test this, but try something similar to this pseudo-code. Note then functions instead of done. The last then returns your data. Sample snippet afterwards to illustrate calling this and handling the result. // modified version of yours var DefineUserData = function LoadUserData() { return Windows.Storage.ApplicationData.current.loca

Categories : HTML

PHPUnit: How to mock a function on a class?
To test this class, you would mock the IntegratedService. Then, the IntegratedService::getResult() can be set to return what ever you like in a mock. Then testing becomes easier. You also need to be able to use Dependency Injection to pass the mocked service instead of the real one. Class: class QueryService { private $svc; // Constructor Injection, pass the IntegratedService object here public function __construct($Service = NULL) { if(! is_null($Service) ) { if($Service instanceof IntegratedService) { $this->SetIntegratedService($Service); } } } function SetIntegratedService(IntegratedService $Service) { $this->svc = $Service } function DoQuery($request) {

Categories : PHP

How to Mock the following case using PowerMock or Easy Mock or Mockito or all
I found the solution. It is something like this in the testClass ParamObject paramObject = get();//Some instance TestClass t = PowerMock.createPartialMock( TestClass.class, "getName", null, paramObject); String expected = "ABC"; PowerMock.expectPrivate(t, "getName").andReturn( expected); PowerMock.replay(t);

Categories : Unit Testing

How to mock/stub callback function with sinon.js?
You can't mock/stub an anonymous function. But you can make a refactoring and stub/mock the named callback. $('.download-modal').on('hide', onHide); var onHide = function() { window.clearInterval(window.periodicalTimer); }; // ... sinon.stub(onHide);

Categories : Javascript

Invoking Overloaded Function on Google Mock
The signature of your method in the mock class is wrong : MOCK_METHOD2(setSize, bool(int w, int h)); and the base class has the method with this signature : virtual void setSize(int w, int h) = 0; I am not sure which compiler you are using, but that should be a compiler error. Fix the signature, and the error should go away : MOCK_METHOD2(setSize, void(int w, int h)); Additionally, class MockFoo : AbstractFoo should be class MockFoo : public AbstractFoo Your problem has nothing to do with googlemock library - but rather with c++. What you are trying to achieve is not possible because of [class.virtual]/1. Next example demonstrates the same problem : struct A { A(int h,int l):x(h),y(l){} int x; int y; }; class AbstractFoo { public: virtual void setSize(int

Categories : C++

How to mock a function used in the object constructor (with Mockito)?
Normally you'd mock the entire object and not just a part of it. But if it's not final, create a subclass of Picture and override the constructor and do your custom thing there. That way you can avoid calling the original constructor and you can test the instance. If it is final then unit testing it becomes quite hard. If you are not actually unit testing this particular class, you should either mock the picture object entirely or not at all. BTW, this is why you shouldn't allow your constructors to do work: it results in code that is hard to test & mock. Separating object initializations from your logic is a good thing. Probably what you'd want here is an additional constructor that takes filename and dimensions as constructor args.

Categories : Java

how to mock jquery calls from within a function using jasmine and sinon
This might seem a little naive, but I'll point it out anyway. It seems to me that you're not actually rendering the view anywhere. I say this simply because none of the code you posted calls .render() on the view and I can't see anything that would suggest it's happening behind the scenes, and that might explain why the JQuery call is behaving the way it is. Rendering views from within a Jasmine spec is usually as simple as this: beforeEach(function () { // some element you want to render your view into $('#testbed').html(view.render().el); }); form_id might be undefined because the element you're looking for is not in the DOM. Can you actually find that element at all from within the function? And from within the test itself? (Also, because that function is bound to an event, I

Categories : Jquery

Mock function with class template parameter in signature
I found the answer, you need to denote the mock methods specifically as template mock methods with a _T template <typename T> struct MockMockable : Mockable<T> { MOCK_METHOD2_T(do_work, void(const int, const T&)); }; More information: https://code.google.com/p/googlemock/wiki/CheatSheet#Mocking_a_Class_Template (Not sure whether to delete or leave this?)

Categories : C++

Uninteresting mock function call bla() && Expected: to be called at least once bla()?
You need to set the expectations on the actual instance of your mocked class which will be called during the test's execution. In your case, you're setting the expectations on the object mockBla which is only constructed then destructed at the end of the test - it is never used. You'll either need to pass the mock object into the CallerClass to use, or allow the CallerClass to create the mock object as a member variable, but then allow the test access to that actual member (via e.g. a getter or allowing the test to be a friend of the CallerClass). An example of passing the mocked object into the calling class would be something like: #include <memory> #include "gmock/gmock.h" class Bla { public: virtual ~Bla() {} virtual float myFunction() = 0; }; class MockBla : public Bl

Categories : C++

Why can't I use midge to mock a function that throws using slingshot's throw+
Following slingshot's code for how it generated a throwable (see here, here and here), I found the following (somewhat contrived) way for generating a throwable that would work when just throwing. (s/get-throwable (s/make-context {:type :user-not-found} "throw+: {:type :user-not-found}" (s/stack-trace) {})) Which renders the result you were expecting from your example. (try+ (try (throw (s/get-throwable (s/make-context {:type :user-not-found} "throw+: {:type :user-not-found}" (s/stack-trace) {}))) (catch Exception e (prn "Caught: " e) (prn "Class: " (.getClass e)) (prn "Message: " (.getMessage e)) (prn "Cause: " (.getCause e)) (prn "Data: " (.getData e)) (throw e))) (catch [:type :user-not-found] p (prn "caught it"))) Hope i

Categories : Unit Testing

My jQuery, AJAX call is getting a null response on a valid return of well-formatted JSON data from a PHP function
I would suggest opening up Developer Tools in Chrome (View > Developer > Developer Tools) and selecting the Network tab. When your AJAX post request is made, it should add an entry there (the "Path" column should be "index.php/controllerFile/get_standby" and the "Method" column should have "POST"). Click the row for the request and check the Response tab to make sure your JSON is there. If the response is empty, your problem is with your PHP code (you might not be printing the JSON returned from that function to the page). Otherwise, it would seemingly be a problem with your JavaScript.

Categories : PHP

Using python's mock patch.object to change the return value of a method called within another method
It can be done with something like this: #foo.py class Foo: def method_1(): results = uses_some_other_method() #testing.py form mock import patch @patch('Foo.uses_some_other_method'): def test_some_other_method(mock_some_other_method): mock_some_other_method.return_value = "specific_value" foo = Foo() the_value = foo.method_1() assert name == "specific_value" Here's a source that you can read: Patching in the wrong place

Categories : Python

Mockito inOrder.verify() fails using mock as function argument
The test fails because the argument to the second executeOn() method call is not the same file as the argument of the first one, since the first file is replaced by another one in file = command.executeOn(file);

Categories : Java

Mock an internal function call of current class under test
How I understand unittesting, is you test the public interfaces of your classes. So in your example, you only assert the result of reset(), and not all the protected and private functions called inside. You then deduce what result onBeforeReset() gave from the result reset() gave. This is of course not a 100% rule. Sometimes you really want to test a private or protected method, for whatever reason (do however consider that this might mean you actually should refactor your code). The creator of PHPUnit has written some thoughts and given some examples (http://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html). Basically you use Reflection to make private and protected methods and properties publicly accesible.

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.