Questions tagged [mocking]

Mocking and faking are ways to isolate code or components to ensure that unit tests run against the testable unit of code only without actually utilizing other components or dependencies of an application. Mocking differs from faking in that a mock can be inspected to assert the results of a test.

Mocking and faking are ways to isolate code or components to ensure that s run against the testable unit of code only without actually utilizing other components or dependencies of an application. Mocking differs from faking in that a mock can be inspected to assert the results of a test.

Reasons for use

In a unit test, mock objects can simulate the behavior of complex, real objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test. If an actual object has any of the following characteristics, it may be useful to use a mock object in its place:

  • The object supplies non-deterministic results (e.g., the current time or the current temperature);
  • It has states that are difficult to create or reproduce (e.g., a network error);
  • It is slow (e.g., a complete database, which would have to be initialized before the test);
  • It does not yet exist or may change behavior;
  • It would have to include information and methods exclusively for testing purposes (and not for its actual task).

For example, an alarm clock program which causes a bell to ring at a certain time might get the current time from the outside world. To test this, the test must wait until the alarm time to know whether it has rung the bell correctly. If a mock object is used in place of the real object, it can be programmed to provide the bell-ringing time (whether it is actually that time or not) so that the alarm clock program can be tested in isolation.

Most commonly, isolation frameworks are used to dynamically build a mock, such as:

15654 questions
8
votes
2 answers

Expect jest mock to have been called with an argument fails in react testing library

I would expect this test to pass but it fails: it('should consume files on drop', () => { const mock = jest.fn(); const file = new File(['file'], 'file.txt', { type: 'text/plain' }); const fileList = [file]; render(
RyanP13
  • 7,413
  • 27
  • 96
  • 166
8
votes
2 answers

How to mock window.location.href with Jest in React?

I'm testing functionality that is not supposed to run locally and need to mock window.location.href: const usePageTracking = (): void => { const location = useLocation(); useEffect(() => { if (!window.location.href.includes("localhost")) { …
thisismydesign
  • 21,553
  • 9
  • 123
  • 126
8
votes
4 answers

How to mock a class method when unittesting in Raku

Suppose I have a class like this: class MyClass { method data-is-valid { return self!get-data ~~ m{^From}; } method !get-data { return 'From Internet'; } } where !get-data method gets some data from Internet. Is it…
Julio
  • 5,208
  • 1
  • 13
  • 42
8
votes
1 answer

Why is mocking so slow to start in Kotlin?

Can anyone tell me why mocking "startup" is so slow in Kotlin? The first test that uses mocks takes seconds (2-3 with mockk and 1-2 with Mockito). The rest take milliseconds. There is no such overhead in Java with Mockito. Way to reproduce: Write…
Paweł Krupiński
  • 1,406
  • 1
  • 14
  • 23
8
votes
2 answers

How do I mock a function which is imported with an alias?

Below I have added some dummy code which exactly represent what I am trying to do. I am importing a function from a class with an alias, I am doing this since the class is running the aliased version itself. Things I have…
8
votes
3 answers

Moq verify method fails even though method will be called

I have some troubles using Moq. Following unit test throws an exception, even though the according method will be called. [TestMethod] public void CreateFinishTest() { // mock methods factoryMock.Setup(f =>…
Robar
  • 1,929
  • 2
  • 30
  • 61
8
votes
1 answer

How to mock @ngrx/store state in Angular 8 unit tests with MockStore and MemoizedSelector

I am trying to create unit testing with jest in angular 8 with RXJS. I want to mock store. I am using https://ngrx.io/guide/store/testing example of Using Mock Selectors. could anyone help me to how can I use MemoizedSelector and MockStore to use…
Jitendra
  • 286
  • 1
  • 2
  • 7
8
votes
1 answer

python mocking sqlalchemy connection

I have a simple function that connects to a DB and fetches some data. db.py from sqlalchemy import create_engine from sqlalchemy.pool import NullPool def _create_engine(app): impac_engine = create_engine( app['DB'], …
user1050619
  • 19,822
  • 85
  • 237
  • 413
8
votes
2 answers

Mocking ApolloClient's client.query method with Jest

Update January 22nd 2020 The solution from @slideshowp2 is correct, but I could not get it to work at all, due to this TypeError: TypeError: Cannot read property 'query' of undefined Well it turned out to be my jest configuration that had…
Anton
  • 101
  • 1
  • 2
  • 5
8
votes
1 answer

testing methods wrapped in blocks with RSpec

In my simplified example of what I'm actually doing, let's say I have 2 calls to the database: Repo.add( something_stringy ) Repo.remove( something_floaty ) and I want to use mocks for the database calls, as the real calls will be tested…
ian
  • 12,003
  • 9
  • 51
  • 107
8
votes
4 answers

jest.mock with named exports how to spy

Lets say I have the following named export in a file customer.ts export const saveDetails = ()=>{} export const loadDetails = ()=>{} assuming I'm using this in another file import {saveDetails, loadDetails} from './customer.ts' I want to mock mock…
tmp dev
  • 8,043
  • 16
  • 53
  • 108
8
votes
1 answer

How to mock raise urllib errors

After reading this in the python docs, I am catching the HTTPError and URLError exceptions in get_response_from_external_api that the make_request_and_get_response (via urllib's urlopen call) can raise: foo.main.py from urllib.request import…
timmy78h
  • 183
  • 1
  • 3
  • 10
8
votes
3 answers

How do I mock a class that doesn't have virtual methods?

Let's assume you have a very well designed Delphi project, which respects the dependency injection and some other good practices. Now let's assume you need to mock a class defined as: TMyClass = class public procedure Method1; procedure…
Rafael Colucci
  • 6,018
  • 4
  • 52
  • 121
8
votes
4 answers

How do I mock boto3's StreamingBody object for processing with BytesIO in Python?

I'm unittesting a function that transforms an element from an S3 object into a pandas DataFrame and need to mock the returned StreamingBody object from boto3 file.py def object_to_df(self, key_name, dtypes): s3_object =…
sam
  • 653
  • 9
  • 21
8
votes
2 answers

Mocking SqlConnection, SqlCommand and SqlReader in C# using MsTest

I came across this answer and I'm interested in implementing the second answer using Fake. Here's another one. I'm not really understanding all the concepts there and I'm still reading and understanding documentation, can someone help using my…
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49