python,git,unit-testing,mocking
I encounter the similar issue before when I do mock test. This answer I followed and it is very helpful is there a way to track the number of times a function is called? One approach is to create a proxy of the instance for which you want to count...
NSubstitute is intended to be used with interfaces. It has some limitations with classes like only being able to work for virtual members. From their documentation: Warning: Substituting for classes can have some nasty side-effects. For starters, NSubstitute can only work with virtual members of the class, so any non-virtual...
There are some issues in your code. In the first example you forgot that patch() is applied in with context and the original code is recovered when the context end. Follow code should work: def test_post(): with patch('domain.one') as mock: instance = mock.return_value instance.addition.return_value = 'yello' url = '/domain' response...
No mock related. If what you want for your test with an in memory file like object you could you StringIO: >>> import StringIO >>> file_like = StringIO.StringIO() >>> file_like.write('ABC') >>> file_like.seek(0) >>> file_like.read() 'ABC' ...
There is no way to change decorators parameters after load the module. Decorators decorate the original function and change it at the module load time. First I would like encourage you to change your design a little to make it more testable. If you extract the body of get_link() method...
java,unit-testing,junit,mocking,mockito
You cannot By verification: The loop invariant is that registered is false. So the loop is not entered if it is true The loop is exited at the bodies start (in this case it is true) if a Throwable is thrown, that is not caught by 'catch(Exception e)' (in...
java,unit-testing,junit,mocking,mockito
String currentAlphabet; private ruleSetUp() { // [snip] Mockito.doReturn(currentAlphabet).when(dummyObj).innerMethod( Mockito.anyInt(), Mockito.anyInt()); } Mockito returns null for every call to innerMethod because you're telling it to. Though you set currentAlphabet whenever next is called, you don't set anything until then. At the time that ruleSetup is called, currentAlphabet is null, so...
android,unit-testing,android-intent,mocking,nfc
It's possible to create a mock tag object instance using reflection (note that this is not part of the public Android SDK, so it might fail for future Android versions). Get the createMockTag() method though reflection: Class tagClass = Tag.class; Method createMockTagMethod = tagClass.getMethod("createMockTag", byte[].class, int[].class, Bundle[].class); Define some constants...
You are mocking the method call in the right place. However, since you are calling the method from an instance, it is a bound method, and thus receives the instance as the first argument (the self parameter), in addition to all the other arguments. Edit: Since Bar is replaced with...
java,spring,junit,mocking,mockito
This worked. Just add the checks for the system properties you set. @RunWith(MockitoJUnitRunner.class) public class AppStartUpContextListenerTest { public AppStartUpContextListenerTest() { } @Mock ServletContextEvent mockEvent; @Mock ServletContext mockServletContext; @Mock Configuration mockConfig; @Mock WebApplicationContext mockWebContext; /** * Test of contextInitialized method, of class AppStartUpContextListener. */ @Test public void testContextInitialized() { System.out.println("testContextInitialized");...
c#,unit-testing,mocking,xunit,nsubstitute
It's a really bad idea to Mock the class you're testing. It can lead to all sorts of weird issues, not to mention tightly coupled tests. If you really want to test this scenario, then you can hand-roll a testable stub: public class TestableDocument : Document { DocumentState _state; bool...
You don't need Sinon to accomplish what you need. Although the process.platform process is not writable, it is configurable. So, you can temporarily redefine it and simply restore it when you're done testing. Here's how I would do it: var assert = require('assert'); describe('changing process.platform', function() { before(function() { //...
python,testing,input,mocking,flexmock
ask doesn't return after the first too-young age; it loops until an appropriate age is entered. As written, you'll need to supply all the strings it might read, then do all your assertions after ask returns. @mock.patch('builtins.input', side_effect=['11', '13', 'Bob']) def test_bad_params(self, input): ask() output = sys.stdout.getline().strip() assert output ==...
java,unit-testing,mocking,cobertura,jmockit
Invoke it using reflection or just mockit.Deencapsulation.newInstance(). Write a test method like this @Test public void privateConstructorCoverage() throws Exception { Deencapsulation.newInstance(TestFactory.class); } Deencapsulation javadoc Provides utility methods that enable access to (ie "de-encapsulate") otherwise non-accessible fields, methods and constructors belonging to code under test. ...
unit-testing,laravel-4,mocking,phpunit,mockery
A mocked class does not execute the real code by default. If you mock the helper it will check that the calls are being made but won't execute the anonymous function. With mockery, you can configure the expectation so that the real method will be executed: passthru(); Try this: $helperMock...
I thought it would be faster to ask rather than go check by myself :) I was lazy and wrong so I did the check by myself and here is the answer. It is the same thing, Mockito.Times() is internally calling the VerificationModeFactory.times() From Mockito.class /** * Allows verifying exact...
c#,unit-testing,testing,mocking,nsubstitute
out parameters are updated using their parameter position as an index. It's explained in the Returns documentation for NSubstitute. So, for your particular case, you are populating the second and third parameters, so you should be setting up your call like this: customerDataAccess.When(x => x.GetCustomerWithAddresses(1, out customers, out addresses)) .Do(x...
c#,unit-testing,dependency-injection,mocking,unity
OK, I managed to do it, using AutoMocking (thanks to Sam Holder for the link) as an example to create a Unity extension. The code is relatively simple: public class AutoFakeExtension : UnityContainerExtension { protected override void Initialize() { Context.Strategies.AddNew<AutoFakeBuilderStrategy>(UnityBuildStage.PreCreation); } private class AutoFakeBuilderStrategy : BuilderStrategy { private static readonly...
python,unit-testing,testing,mocking,py.test
To use patch in these kind of tests you should use create parameter that will force to create the attribute if not exist. So your test should do something like this: def test_MyContextManager(): with patch.object(MyClass, 'myfunc', create=True, return_value=None) as mock_obj: with MyContextManager(): pass ...
spring,unit-testing,mocking,mockito,mockmvc
1.) Why does the mock not trigger? I suppose it does not check for value equality in the object, but for object identifiers, which are not the same... By default, Mockito delegates to your object's equals method. If you haven't overridden that, then it checks references by default. The...
You can use Mockito and PowerMock: import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(B.class) public class C { @Before public void setUp() throws Exception { A a = spy(new A()); when(a.run()).thenReturn("mock return");...
node.js,unit-testing,mocking,promise,mocha
So another approach is to use a combination of rewire and deride. var should = require('should-promised'); var rewire = require('rewire'); var Somefile = rewire('./path/to/file'); var deride = require('deride'); var sut, mockSql; before(function() { mockSql = deride.stub(['query']); Somefile.__set__('sqlServer', mockSql); sut = new Somefile(); }); describe('getting patient notification numbers', function() { beforeEach(function()...
php,mocking,phpunit,expectations
Typically, you should not mock/stub your system under test itself. Since in your test case, the $this->observerMock object is itself a stub object (which mimicks the interface of another class, but without providing any implementation). This means that the methods m1 and m2 are also mock methods that will not...
python,unit-testing,mocking,wsgi,assert
What you need to do in your unittest to test http_exception return case is: patch cred_check.methodA to return False Instantiate a MyClass() object (you can also use a Mock instead) Call MyClass.methodB() where you can pass a MagicMock as request and check if the return value is an instance of...
angularjs,testing,mocking,jasmine,karma-runner
Try something like this: describe('Using externally defined mock', function() { var ConfigServiceMock; beforeEach(module('mocks')); beforeEach(module('services.configService', function($provide) { $provide.factory('ConfigService', function() {return ConfigServiceMock;}); })); beforeEach(module('services.loginService')); beforeEach(inject(function (_ConfigServiceMock_) { ConfigServiceMock = _ConfigServiceMock_; })); // Do not combine this call with the one above beforeEach(inject(function (_LoginService_) { LoginService = _LoginService_;...
ruby-on-rails,ruby,rspec,mocking
I would rather try to assert the externally visible effects. Suppose you have a SomeGem.configuration method that you can use to retrieve the configured values, then you could write describe 'configuration block' do subject do lambda do SomeGem.configure do |config| config.username = "hello" config.password = "world" end end end it...
c#,.net,unit-testing,mocking,moq
After reading the MOQ's manual 3rd time I finally was able to find the way to do this. That was surprisingly simple: mockObjectContext.Setup(m => m.SP_IsUserAllowedToDoThings(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ObjectParameter>())).Callback<string, string, ObjectParameter>((a, b, c) => { c.Value = true; }); ...
c#,unit-testing,mocking,rhino-mocks
You have to call "CallOriginalMethod" method with "OriginalCallOptions" enumeration.(By the way, you use RhinoMocks's old API...) Change your calls to: fakeBoard.Stub(x => x.AddPlayer(x => x.AddPlayer(Arg<Player>.Is.NotNull))) .CallOriginalMethod(OriginalCallOptions.NoExpectation) .Return(true); One more thing, the method "PlayGame" must be a virtual method(to apply this behavior...)...
c#,unit-testing,mocking,nunit,moq
If you want to mock the ExecutAsync method you can do it like this: Mock<IApiRequest> mock = new Mock<IApiRequest>(); mock.Setup(x => x.ExecuteAsync<UpcomingMovies>(It.IsAny<RestRequest>())) .Returns(Task.FromResult<UpcomingMovies>(/** whatever movies **/)); if you want to mock for a particlur request, replace It.IsAny<RestRequest>() with a reference to your request. To effectively test your class you need...
java,hadoop,mocking,hbase,storm
Edit 'Unit Test' is to verify, and validate a particular 'unit of code'. If that 'unit of code' depends on external calls, then we mock those calls to return certain values. If you don't invoke the 'actual unit of code' from your test case, then what is the point in...
For this you don't even need mocking, lets say foo is defined in file code.py, in test file code should be like this from code import A A.props = <mockvalue> and then your testing code. But if you to want to do something little more sophisticated like mocking post ,...
javascript,unit-testing,mocking,typescript,monkeypatching
The sinon library (which has bindings for TypeScript) does this already, with special support for faking XMLHttpRequest (and timers). Using that where possible seems like the best option. There's lots of ways to get around the type checking in TypeScript e.g. Assigning a value of type any (always permitted) Writing...
ruby,mocking,minitest,stubbing
I ended up changing the class that was being tested. Called a new function 'get_input' which then called 'gets' and then stubbed the 'get_input' method.
python,mocking,python-unittest
To do that you can mock the class function with the @patch like that from mock import patch # Our class to test class FooObject(): def update(self, obj): print obj # Mock the update method @patch.object(FooObject, 'update') def test(mock1): # test that the update method is actually mocked assert FooObject.update...
java,unit-testing,mocking,testng,mockito
You have to keep the stubbing together with the mocked objects. E.g. final Response response = Response.ok().build(); IClient inner = new IClient(client, propConfig){ Builder buildRequest(MultivaluedMap<String, Object> Headers, WebTarget target){ Builder builder = mock(Builder.class); when(builder.post(any(Entity.class)).thenReturn(response) return builder; } }; assertNotNull(inner.doLogin()); Yet there is a small problem - this test does test...
Probably you want to use WhenCalled method: class Program { static void Main() { List<IEmailConfiguration> performedCalls = new List<IEmailConfiguration>(); // preparing test instance var mailerMock = MockRepository.GenerateStrictMock<Mailer>(); mailerMock.Expect(x => x.SendMessage(Arg<DummyEmailConfiguration>.Is.Anything)) .WhenCalled(methodInvocation => // that's what you need { var config = methodInvocation.Arguments.OfType<IEmailConfiguration>().Single(); performedCalls.Add(config); }); // testing for...
I figured it out thanks to this: http://mock.readthedocs.org/en/latest/examples.html#mocking-unbound-methods The trick is to add autospec=True in @patch.object(Foo, 'bar', autospec=True). class Foo(object): def __init__(self): self.hello = "Hey!" def bar(self): return self.hello + " How's it going?" def side_effect_foo_bar(*args, **kwargs): return args[0].hello + " What's up?" class TestFoo(unittest.TestCase): @patch.object(Foo, 'bar', autospec=True) def test_bar(self,...
java,unit-testing,junit,mocking
you don't have to test getSubString or length. it's already tested by guys from sun and your db provider. what you should test is that you are using them correctly. apparently you cannot do it by mocking clob because you would test nothing or you would have to implement your...
node.js,unit-testing,mocking,mocha
With mocha tests you have an optional done callback that makes testing async functions easier, like this: it('should send a verify SMS', function(done) { var data = {}; var code = 1; methods.sendVerifySms(code, data) .then(function(actualCode) { should(actualCode).equal(code); done(); }); }); I would also have some feedback to offer on the...
java,unit-testing,mocking,jmockit
Full example code which meets the given constraints: public static class StreamGobbler extends Thread { public StreamGobbler(String type) {} public String getOutput() { return null; } @Override public void run() {} } public static class TestedClass { public String doSomething() throws InterruptedException { StreamGobbler sg1 = new StreamGobbler("OUTPUT"); sg1.start(); StreamGobbler...
You put your exception into the wrong side effect. Calling make_request_response() now first returns the mock_bad mock, which by itself won't raise that exception until called. Put the exception in the mock.patch.object() side_effect list: error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found') mock_good = mock.Mock() mock_good.return_value = [{'name': 'foo', 'id': 1}] upsert =...
My approach has been to create the logic of the singleton as a trait and then have the object extend the trait. This allows me provide the Singleton as a default or implicit argument, but provide a stubbed out implementation for testing trait FeedLogic { def getLatestEntries: Future[List[FeedEntry]] { /*...
java,spring,junit,mocking,spring-test-mvc
The 406 Not Acceptable status code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString(); or configure your own HandlerMethodReturnValueHandler. Check this similar question Returning JsonObject using @ResponseBody in SpringMVC
mocking,asp.net-identity,owin,nsubstitute
SignInManager has some virtual methods, which NSubstitute will be able to mock (keeping in mind that some real code will execute because it is a class with some non-virtual members). Or you could wrap the features you need from SignInManager with your own interface, mock that in tests, and use...
python,django,python-2.7,unit-testing,mocking
From your function here, stream seems to be a class. Since you create an instance of that class and then you call the open method on that instance, you need to do mock_stream.return_value.open.return_value = False in the test function....
methods,mocking,phpunit,magic-methods
You should use the PHPUnit at() method to check method invocation at certain index. So you can use the following code: $this->attributeMock ->expects($this->at(1)) ->method('getData') ->with('additional_data') ->willReturn('some value'); $this->attributeMock ->expects($this->at(0)) ->method('getData') ->with('is_default') ->willReturn('something'); You can check the following article for some reference: http://www.andrejfarkas.com/2012/07/phpunit-at-method-to-check-method-invocation-at-certain-index/...
php,unit-testing,mocking,phpunit
the exactly() method is for asserting how many times an mocked method will be called. Unless you are using $this->at() for the mocked behavior, you don't specify the arguments for a specific call. exactly(0) says that the number of calls should be 0. Change your mock to this: $logger->expects($this->any()) //Or...
This is very easy to do with JMockit: public class ClassUnderTestTest { interface SomeService { int doWork(); } class ClassUnderTest { private final SomeService service; ClassUnderTest() { service = new SomeService() { @Override public int doWork() { return -1; } }; } int useTheService() { return service.doWork(); } } //...
python,unit-testing,mocking,python-asyncio
Since mock library doesn't support coroutines I create mocked coroutines manually and assign those to mock object. A bit more verbose but it works. Your example may look like this: import asyncio import unittest from unittest.mock import Mock class ImGoingToBeMocked: @asyncio.coroutine def yeah_im_not_going_to_run(self): yield from asyncio.sleep(1) return "sup" class ImBeingTested:...
junit,mocking,mockito,jboss-arquillian,verify
This can be done via multiple ways but I will go over one. First, because you use @Inject to get your instance of OrganisationService, then I will not mess around with mocking the new OrganisationService() constructor call. Instead we can setup a getter method for the OrganisationService, then mock it....
Function defaults are set and stored with the function object when the function definition is executed. Mocking platform.machine works fine, but the default value for the arch argument has long since been set by calling platform.machine() and using the return value. The expression is not used when test() is called....
You could create an anonymous controller in your spec and include your module in it. When you've got that, you can test it like a normal controller action/method. So, add something along the lines of this to your spec: controller(YourController) do include YourModule def index render text: 'body' end end...
spring,unit-testing,mocking,spring-boot,mockito
I had to manually register the MessageSource in my test configs and create a constructor in the ControllerAdvice to add parm MeasageSource. Also had an issue with MessageConverter not being found for my JSON response, had to set the convert in ExceptionHandlerExceptionResolver. Edited my question to show the reflected changes.
python,mocking,api-key,python-unittest
Separate out the tests for API calls and for the Client.getContext() method. For explicitly testing the API calls, patch a request object... import client import httpretty import requests from mock import Mock, patch ... def testGetQueryToAPI(self): """ Tests the client can send a 'GET' query to the API, asserting we...
c#,asp.net,unit-testing,linq-to-sql,mocking
Looks that it is not very easy task. And I think you should use some popular and tested library or tool. My recommendation is to use the MiniProfiler. It allows to capture all SQL queries (also includes a support of LinqToSql). It has a good UI and API to interact...
You are still instantiating a real PaymentManagerWebService in validatePaymentmsg(), so the mocks do not help. You can't mock construction of local variables with EasyMock, but you can with PowerMock. So if changing the code to receive and instance of PaymentManagerWebService is not an option, mock its construction with PowerMock. @RunWith(PowerMockRunner.class)...
ios,unit-testing,mocking,ocmock
You want to use a partial mock, somehow like this: id peerMessage = [OCMockObject partialMockForObject:[[PeerMessage alloc] init]]; [[[peerMessage stub] andReturn:@"<valid>"] content]; XCTAssert([peerMessage isTextMessage]); This way, the real implementation of isTextMessage, the one you want to test, is invoked, but you can still stub out other methods on the object....
mocking,mockito,specs2,callbyname
First of all you need to make sure that specs2-mock.jar is placed before mockito.jar on your classpath. Then be aware that the f passed to the answers method is a Function0. For example class InvokeLater { def apply(f: =>Int): Unit = { // do something ... f // do some...
The http.Head function simply calls the Head method on the default HTTP client (exposed as http.DefaultClient). By replacing the default client within your test, you can change the behaviour of these standard library functions. In particular, you will want a client that sets a custom transport (any object implementing the...
python,django,unit-testing,mocking,celery
I found a problem and it was pretty silly. Described here and Here: The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. I need to change: @mock.patch('django.core.mail.mail_managers') with @mock.patch('path.to.tasks.mail_managers') ...
java,mocking,tdd,guice,roboguice
You can inject a provider which provides 'HTTPRequest' instances in your code. class ModelClass { @Inject Provider<HTTPRequest> httpRequestProvider; public void populate() { HTTPRequest request = httpRequestProvider.get(); } } Then, in your test code, you can mock the 'httpRequestProvider' to return mock 'HTTPRequest' instances. Provider<HTTPRequest> mockHttpRequestProvider = mock(Provider.class); when(mockHttpReqestProvider.get()).thenReturn(yourMockHTTPRequestObject); // Set...
javascript,angularjs,unit-testing,mocking
In case anyone wants to do what I have done (separate your mocks into different files so you don't need to copy-paste things a lot), here is what I have found out. // /test/mock/UserService.mock.js (function() { "use strict"; angular.module('mocks.Common').service('UserService', mock); mock.$inject = ['$q', 'User']; function mock($q, User) { return {...
First base things about patch: Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone. If new is omitted, then the target is replaced with a MagicMock. If patch() is used as a decorator...
c#,unit-testing,mocking,nunit,nsubstitute
NSubstitute like most mocking frameworks can only intercept calls to virtual methods. It is able to stop the call to Broadcast, because it is virtual. You need to make EmitTo virtual if you want to stop it being called. It needs to be: public virtual void EmitTo(string connectionId, ChatMessage message)...
According to Where to path you should patch os_name in production_code instead of os.name. Moreover write your test by use decorator form instead with structure make it more readable: class TestProduction(object): @patch("production_code.os_name","posix") def test_platform_string_posix(self): assert_equal('posix-y path', production.platform_string()) ...
There are a couple issues with your current approach: You typically use mocks/stubs/fakes/whatever, i.e. providing a fake implementation of a collaborator class, when testing another class in isolation. For example, you could be unit testing some controller in isolation and provide mocks for each of its collaborating objects (a fake...
python,unit-testing,testing,mocking
When the iterator yields an item, ProcessorMock is called to produce the item, but the item itself is never called. Rather than asserting that item was called, you should be making those assertions about ProcessorMock: ProcessorMock.assert_called_with(vals[idx]) ...
java,unit-testing,mocking,mockito,builder-pattern
Use PowerMockito instead. There you can define that whenever you have a call to a constructor of DAO, return my mocked object instead of returning actual DAO object. Please refer this to learn how to use PowerMockito.
python,mocking,py.test,python-mock
The simpler and cleaner way to do it is with mock.patch("mymodule.requests.post", side_effect=[Mock(status_code=400), Mock(status_code=200)]) as mock_post: mymodule.some_function() patch create mock_post object by MagicMock(side_effect=mock_responses) and replace mymodule.requests.post reference. You can also use mock_post to check post() calls by something like: mock_post.assert_has_calls([mock.call(first_url, first_params), mock.call(second_url, second_params)]) You can do the same work by build...
It should be configured and verified in the following way: @Grab('org.spockframework:spock-core:0.7-groovy-2.0') @Grab('cglib:cglib-nodep:3.1') import spock.lang.* class Test extends Specification { def "foo"() { given: def a = Mock(A) B b = new B() when: b.b(a) then: thrown(RuntimeException) 1 * a.a() >> { throw new RuntimeException() } } } class B {...
You can simplify your mock with returnValueMap. $valueMap = [['k1', 'v1'], ['k2', 'v2']]; $registryMock->expects($this->exactly(count($valueMap)) ->method('get') ->will($this->returnValueMap($valueMap)); This method can map any number of parameters to a value. And now you don't have to worry about the order of the calls and aren't as tightly coupled for this method call. For...
javascript,angularjs,unit-testing,mocking,jasmine
When you call var sock = new webSocket(); new instance is being created from the webSocket constructor. Because of your design, this sock variable (webSocket instance) is not publicly exposed, therefore is not available in a test suite. Then, you define a property onmessage on this sock instance: sock.onmessage =...
javascript,angularjs,unit-testing,mocking,jasmine
First of all, make mock service method return Promise object: mock__mdSidenav = function(component) { return { isMock: true, close: function() { return $q.when(); } } }; Then inject it into controller instance: menuCtrl = $controller("MenuCtrl", { $scope: $scope, $mdSidenav: mock__mdSidenav }); And finally, write some expectation: it('should create the $mdSidenav...
java,unit-testing,resources,mocking,directory-structure
src\test\resources is a good place for resources you need for unit-testing, if you are using mavens standard directory layout. Read more about the different directories here: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html...
javascript,node.js,unit-testing,mocking
You can emit the 'data' event at will because SerialPort implements the EventEmitter interface. Just use .emit(). This code will log "woot" to the console even though the serial interface didn't actually receive any data. It fakes it with .emit(). var serialport = require("serialport"); var SerialPort = serialport.SerialPort; var sp...
Why mess around with __iter__? It seems to me that you want to mess with __contains__: >>> import mock >>> m = mock.MagicMock() >>> d = {'foo': 'bar'} >>> m.__getitem__.side_effect = d.__getitem__ >>> m.__iter__.side_effect = d.__iter__ >>> m['foo'] 'bar' >>> 'foo' in m False >>> m.__contains__.side_effect = d.__contains__ >>> 'foo'...
The Ruby case handles the === comparison without an explicit call to class, although making the explicit comparison on the result of test.class makes the above code work. If you can't do that though, as you've said above, you may not be able to get a case like this to...
java,junit,static,mocking,mockito
While putting a null pointer check in the static method would avoid the NPE being thrown; it it a bit of a code smell. I would suggest that the jTextArea be declared as non-static which in turns implies that the printInMain method would also be non-static. This then leads to...
python,unit-testing,mocking,python-mock
Think you can use side effect to set and get value in a local dict data = {} def set(key, val): data[key] = val def get(key): return data[key] mock_redis_set.side_effect = set mock_redis_get.side_effect = get not tested this but I think it should do what you want...
ruby-on-rails,rspec,mocking,simplecov
http://pastebin.com/kqJ39MBk Test should be looked like this one
This is happening because your mock is actually overwriting the entire requests module in your code. Here is how you can debug this: In your code, add this: try: requests.post('', data='') except (requests.ConnectionError, requests.Timeout): was_successful = False except Exception, err: import pdb pdb.set_trace() When you run the test, you will...
ios,objective-c,unit-testing,mocking,ocmockito
All standard DDLog macros call +[DDLog log:level:flag:context:file:function:line:tag:format:], so with OCMock, you would verify the DDLogInfo was called by: - (void)testMethodCallsDDLogInfo { id mockDDLog = OCMClassMock([DDLog class]); [obj methodThatCallsDDLogInfo]; OCMVerify([mockDDLog log:YES level:DDLogLevelAll flag:DDLogFlagInfo context:0 file:[OCMArg anyPointer] function:[OCMArg anyPointer] line:58 tag:[OCMArg any] format:[OCMArg any]]); } Unfortunately, with this strategy you must hard-code...
c#,unit-testing,dependency-injection,mocking,autofixture
This works: public class PropertyBuilder : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var pi = request as PropertyInfo; if (pi != null) { if (pi.IsDefined(typeof (DependencyAttribute))) return context.Resolve(pi.PropertyType); //"hey, don't set this property" return new OmitSpecimen(); } //"i don't know how to handle this request - go...
unit-testing,junit,mocking,mockito,abstract-class
Well, this code below works fine, just tell me if I need to add some comments to explain what I wrote, ok? (hey, I am using Mockito 1.10.8): import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; abstract class AbstractClassToTest { public abstract String doSomething(); } class...
python,unit-testing,mocking,python-mock
The simplest way is to grab your own reference to the original function before patching. Patching can be done on an individual instance of the class: original_foo = f.foo with patch.object(f, 'foo') as mock_foo: def side_effect(a): print "mock foo", a return original_foo(a*2) mock_foo.side_effect = side_effect f.foo(2) ...or by patching the...
java,mocking,jersey,integration-testing,inject
Providers shouldn't have to be mocked. It is handled by the framework. Any providers you want added, just register with the ResourceConfig. I don't know what you care doing wrong in your attempt at this, but below is a complete working example where the ContextResolver is discovered just fine. If...
If $params->redirect('/signin'); is the line it breaks i think you should be able to solve this with. In the setup: $this->app = $this->getMock( '\Slim\Slim', array('redirect'), array(array('mode' => 'testing')) ); array(array( is on purpose as it is an array of constructor arguments and your constuctor looks like it wants an array...
__subclasses__ is not part of the class spec. It is part of the metatype of the class (type here). Python always looks up special methods on the type, never directly. If and when Python needs to call __subclasses__, it'll not do so directly, it'll use type(classobj).__subclasses__(classobj) to look up the...
You need to design your code so that you only have dependecy to the IHubProxy interface You can look at my .NET client library to see how it can be solved https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Client.DotNet In my case some of the code needed the actual concrete HubProxy so what I did was to...
According to https://docs.python.org/2/library/random.html, the RNG was changed in Python 2.4 and may use operating system resources. Based on this and the other answer to this question, it's not reasonable to expect Random to give the same result on two different versions of Python, two different operating systems, or even two...
ruby-on-rails,activerecord,rspec,mocking
The reason this isn't working, is that the delete action loads its own version of car - it isn't using the local variable you have declared locally to your spec. So any stubs you add to your local variable will not actually exist on the brand new copy of car...