How to let MagicMock behave like a dict?

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’ in m True

java: how to mock Calendar.getInstance()?

You can mock it using PowerMock in combination with Mockito: On top of your class: @RunWith(PowerMockRunner.class) @PrepareForTest({ClassThatCallsTheCalendar.class}) The key to success is that you have to put the class where you use Calendar in PrepareForTest instead of Calendar itself because it is a system class. (I personally had to search a lot before I found … Read more

Is it possible to verify a mock method running in different thread in Mockito?

It is very likely that the Runnable hasn’t been executed yet by the asyncTaskExecutor when you verify the invocation, resulting in a verification error in your unit test. The best way to fix this is to join on the generated thread and wait for execution before verifying the invocations. If you cannot get the instance … Read more

Mock AsNoTracking Entity Framework

Looking at the source code of the AsNoTracking() extension method: public static IQueryable AsNoTracking(this IQueryable source) { var asDbQuery = source as DbQuery; return asDbQuery != null ? asDbQuery.AsNoTracking() : CommonAsNoTracking(source); } Since source (your DbSet<Product> you’re trying to mock) is indeed a DbQuery (because DbSet is deriving from DbQuery), it tries to invoke the … Read more

How to Mock an HTTP request in a unit testing scenario in Python

Starting a web server for unit testing is definitely not a good practice. Unit tests should be simple and isolated, which means that they should avoid performing IO operations for example. If what you want to write are really unit tests then you should craft your own test inputs and also look into mock objects. … Read more

How to mock using patch relative paths?

I used Dan Passaro’s solution till I came across this one using patch.object – which looks even better to me: from unittest.mock import patch, from .. import monkey […] @patch.object(monkey, ‘ook’, Mock(return_value=None)) def test_run_ook (self, mock_ook): self.assertIsNone(monkey.ook()) mock_ook.run.assert_called_once_with(”) Advantages: No need for the boilerplate code that is __name__ + ‘.object_to_be_mocked’ All dependencies of the test … Read more

Testing Java Sockets

If I was to test the code, I’d do the following. Firstly, refactor the code so that the Socket isn’t directly instantiated in the method you want to test. The example below shows the smallest change I can think of to make that happen. Future changes might factor out the Socket creation to a completely … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)