Questions tagged [mocking]

1

votes
1

answer
100

Views

How to test a method that makes calls to a database

I have several methods that make connections to a database and I can't figure out how to write unit tests for them. Here is a sample of what I'm talking about. public static User GetByPendingUserId(int a_PendingUserId) { User l_User = new User(); SqlConnection l_conn = DbHelp.CreateSqlConnection();...
tayopi
0

votes
0

answer
16

Views

How to mock GCP's storage in golang?

I'm really new to mocking third-party library in go, I'm mocking cloud.google.com/go/storage right now I'm using mockery. This is my current interface: //Client storage client type Client interface { Bucket(name string) BucketHandle Buckets(ctx context.Context, projectID string) BucketIterator } //B...
kkesley
0

votes
0

answer
4

Views

Mocking classes with Jest

Given I have a class that calls a function doStuff like so: const myService = require(`./myService`), service = new myService(); exports.doStuff = async (callback) => { try { const data = await service.doOtherStuff(); //I want to mock this return callback(null, data); } catch (err) { callback(new Er...
Tikkes
0

votes
0

answer
3

Views

Chain Multiple UI interactions using moxios

I have to test a scenario where I click on a selection in dropdown verify dom content then click on second selection in dropdown verify dom content and then click on first selection again and verify dom content I have been looking at moxios documentation and I have tried to wrap moxios.wait inside e...
Praveen Banthia
1

votes
2

answer
1.2k

Views

How to mock Push notification native module in React native jest tests?

When using the module react-native-push-notification, I had this error: FAIL __tests__/index.android.js ● Test suite failed to run Invariant Violation: Native module cannot be null. at invariant (node_modules/fbjs/lib/invariant.js:44:15) at new NativeEventEmitter (node_modules/react-native/Libra...
BigOther
1

votes
1

answer
45

Views

How can I mock a simple method using Moq framework?

Let's say I've a simple method which checks whether the passed number is Even & returns a boolean value. I'm new to mocking & trying it out. How can I mock this method using Moq framework? public bool isEven(int x) { bool result = (x % 2 == 0) ? true : false; return result; }
Tim Smith
4

votes
1

answer
163

Views

Jest - How to get coverage for mocked classes and implementations

I'm currently working on a project where I'm using Jest for unit testing and code coverage. Everything is working fine, except coverage for mocked classes/methods. I don't seem to get the desired coverage results. I've tried to find something in the Jest docs and searched online for an answer, but I...
0

votes
0

answer
7

Views

How to check how many rows have been updated

Firs time using Go, so kind of stuck. I am using sqlmock to mock my queries. Here is how i have set it up ctx := context.Background() db, mock, _ := sqlmock.New() rows := sqlmock.NewRows([]string{'account_id', 'home_id', 'zip_code'}). AddRow('account-uuid-1', 'home-uuid-1', 'xxxx'). AddRow('account-...
Em Ae
1

votes
2

answer
59

Views

How to mock Spark DataFrameReader using scala?

I want to unit test code that read DataFrame from RDBMS using sparkSession.read.jdbc(...). But I did't find a way how to mock DataFrameReader to return dummy DataFrame for test. Code example: object ConfigurationLoader { def readTable(tableName: String)(implicit spark: SparkSession): DataFrame = { s...
dytyniak
1

votes
0

answer
17

Views

when using jmockit, how to batch mock classes by special class and do inverse

In the spring environment using Jmockit, I usually want to test a class that needs to mock many other many classes (which this class depends on). E.g: There are now Class1, Class2, ..., Class20. Class1 depends on Class2, Class3, ..., Class20 (via spring ioc). I want to test Class1, and need mocks fo...
Ichen Wenjin
1

votes
1

answer
501

Views

reactjs / jest : unable to populate react-apollo component with data using MockedProvider?

I have written simple react-apollo component which uses graphql query to retrieve data from schema. On execution component works fine but, when I am writing test case for this component using jest framework together with MockedProvider(i.e. component of react-apollo/test-utils). I am unable to popul...
Pramod Jadhav
1

votes
1

answer
76

Views

Testing file i/o with Perl - frameworks

I have the following command in pl script: mkpath($my_dir,0,0777); I want to test instances when it encounters errors when executing this command. Currently, I change permissions of the parent directory, or some other such change to the file system, to force an error. How would I set up a unit test,...
paulj
1

votes
1

answer
319

Views

How do I use Mock in Spock to do tests in Grails?

I am trying use mock to the domains class but in findBy is not working, show that the class is null. At last time give this error: 'C:\Program Files\Java\jdk1.8.0_144\bin\java' -ea -Didea.test.cyclic.buffer.size=1048576 '-javaagent:C:\Users\pedro.borborema-nub\AppData\Roaming\JetBrains\IntelliJ IDE...
Pedro Henrique
1

votes
1

answer
191

Views

SNMP4J How Mock a GETBULK Request?

I need to mock a GETBULK request with snmp4j in java. But I don't understand how to do it. More specific i don't understand how create TreeEvent for create response List and how answer to client. I've a snmpwalk like this public void sendWalk(String community, String ipAddress, int port, String oidV...
FiliRnd
1

votes
0

answer
71

Views

How to mock system call with argument in whole directory?

I have a directory in my app which has several test cases. Those test cases use some third party software using either `` or system calls. And I need to mock those calls. What I can't figure out is how do I mock those calls for that particular directory? I had been trying Test::Mock::Cmd But I can...
Ishan Bhatt
1

votes
2

answer
1.5k

Views

Mock an object inside a method in JUnit

I'm trying to get to grips with JUnit & Mockito etc. I currently have a method with the below line. ObjectMetadata metadata = getMetadata(path.toString()); Is there any way I can mock it? I've tried things like the below Whitebox.setInternalState(, 'metadata', 'abc'); but I just get org.powermock.r...
pac
1

votes
1

answer
353

Views

How do you stub a method to return an array

I have DocumentService class like this: namespace App\Services; use App\Api\StorageServiceInterface; class DocumentService { private $storageService; function __construct(StorageServiceInterface $storageService) { $this->storageService = $storageService; } public function createFolder(User $user) {...
Raghavendra N
1

votes
0

answer
169

Views

How to mock MongoDB using native Node.js driver for testing error?

How to test mongodb errors in Node.js using native driver? I found many related questions to this subject but I need to test my code in case an error rises.
1

votes
0

answer
581

Views

Mocking ToListAsync on a Mock<DbSet<T>> using Moq

I've got a method that converts a List to a DbSet which I use when mocking the data my database context should return. For example: MockedDatabaseContext.Setup(u => u.SomeTable).Returns(GetDbSet(ListOfItems)); However the method I'm trying to write a unit test for uses the ToListAsync method at one...
Jeroen
1

votes
0

answer
74

Views

Mocking context in node.js using express and azure mobile apps for Mocha testing

I have an express app running as an Azure Mobile app. This has a bunch of api methods that are fairly straightforward and just read from a sql database. For example - this is what one looks like (Things.js): var logger = require('../logger/logger.js') module.exports = { get: function(req, res, next)...
Ross Vernal
1

votes
1

answer
20

Views

Understanding Class Mocking

for controller test I have mocks like bookService = createMock(BookService.class); ReflectionTestUtils.setField(homeController, 'bookService', bookService); here I mocked the services. for unit test of service class I have mocked Repository classes bookRepository = createMock(BookRepository.class)...
valen ezu
1

votes
1

answer
63

Views

How to redefine python3 MagicMock magic method?

I need to redefine MagicMock's magic method in the child class and then use child class for testing, so I've tried: from unittest.mock import MagicMock class MockForTest(MagicMock): def __lt__(self): return self t1 = MockForTest() print(t1.__lt__()) # prints NotImplemented But why NotImplemented? I...
Alexey
1

votes
1

answer
702

Views

React Jest - Mock a function with callback

I'm trying to write a test for following code var throttle = require('lodash.throttle'); search = throttle(async (searchTerm:string) => { const response = await AxiosWrapper.Instance.post(this.props.url, { 'searchTerm': searchTerm }); this.setState({ searchResult: response.data as ISearchResult, sho...
nelly2k
1

votes
2

answer
66

Views

Mock urlopen in unknown subpackage

I want to mock out calls to urllib.request.urlopen in a module. It works when it's a single file, but when I put it in a package and import the module in the package's __init__.py, I cannot mock it out anymore. Reproduction Imagine I have two modules in a test package: module.py from urllib.request...
J0hj0h
1

votes
0

answer
96

Views

NSubstitute Mock MVC ActionResult Attributes

I want for the Attributes associated to a controller action to be called during the test. E.g. Code [TestMethod] public void UserRegistersWithNonMatchingPasswords() { var model = GetModel(); var controller= GetController(); controller.Register(model); //This is an ActionResult method AccountReposito...
Uchenna Okafor
1

votes
0

answer
904

Views

Mocking default exported function with Jest says it wasn't called but it was

[EDIT - POSSIBLE SOLUTION] So I realised that my componentWillMount is an async method since it is using an async fs wrapper to do fs operations. So I made the beforeEach function argument async and awaited on the Enzyme.shallow. This seems to have worked. It just came to me that if it's async maybe...
Andreas Andreou
1

votes
1

answer
309

Views

Mocking functions for handler unit test

I am stuck over testing with mocking, Here is my route for handler: r.Handle('/users/{userID}', negroni.New( negroni.HandlerFunc(validateTokenMiddleware), negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { getUserDetailsHandler(w, r, db) })), )).Methods('GET') And here is m...
saket
1

votes
0

answer
51

Views

Some hard mock problems in java 1.4, junit 3.8.1 and jmock 1.2

I have such problem, as topikstarter here - Using PowerMockito.whenNew() is not getting mocked and original method is called But I have java 1.4, junit 3.8.1 and jmock 1.2 - and no annotations, of course. Problem is as it seems in this link - I have a method, which makes new Example(), and then call...
Torevill
1

votes
1

answer
78

Views

Mocking class instantiated in other class in Magento

I'm trying to learn more on testing but unfortunately I have to do it in Magento 1.9.* :) Consider the following code (GDPR related)... class Vendor_Module_Helper_Data { public function __construct() { $this->config = Mage::helper('vendor_module/config'); } public function anonymizeEmail(Mage_Custo...
Maarten Troonbeeckx
1

votes
0

answer
665

Views

Mocking Inherited Classes with Jest

I am extending net.Socket. In doing so, I am overriding the connect method as follows. class ENIP extends Socket { constructor() { super(); this.state = { session: { id: null, establishing: false, established: false }, error: { code: null, msg: null } }; } connect(IP_ADDR) { const { registerSession...
canaan seaton
1

votes
1

answer
315

Views

Inject mocks into class before constructor's logic comes on

Imagine, we have a class, in which a lot of logic is being executed inside a constructor. A question: how to inject mocks in such class before constructor's logic gets executed? Additional info: This class is not written by me and I do not want to violate the existing interface in this class by cha...
Andrey Ilyunin
1

votes
0

answer
276

Views

Manual mocks in Jest not working

I would like to manually mock a function that makes a request to an external API. The function looks like this: module.exports = function suggestions(token, query) {} I created an __mocks__/suggestions.js adjacent to the file which looks like: module.exports = function suggestionsMock(token, query)...
vamsiampolu
1

votes
1

answer
96

Views

PhpUnit testing method with that have variable argument array

My scenario is that I am testing a method which calls another method from a library that takes an array with two keys ['id'=>123, 'timestamp'=>microtime()]. I can put this microtime as an argument to the method I am testing but is there a way that I could make this test so that I test all keys excep...
Zintu
1

votes
0

answer
131

Views

Get request headers (cookies) in routingdsl in play framework for java

I am still learning Play framework for Java. I am trying to create a test case where I am mocking server. In there, I am defining url and response using RoutingDSL. However, I can't seem to find any way to access request headers (actually I am trying to see if client is sending proper cookies). Here...
Dusan Kostic
1

votes
1

answer
336

Views

fetch-mock calls the actual API instead of mocking the request

Given this code: const fetch = require('isomorphic-fetch') module.exports = function suggestions (...args) { // some error handling code return fetch(MY_ENDPOINT) } I have found that when using fetch-mock like this: require('isomorphic-fetch') const fetchMock = require('fetch-mock/es5/server') fetch...
vamsiampolu
0

votes
0

answer
8

Views

How to mock data from the library in Jest testing?

How should I mock data from the library for jest testing? I have tried jest.mock('apollo-link-http') but not able to mock httpLink from it.
Muzamil ijaz
1

votes
1

answer
516

Views

Jest: Mocking a function per test not working

In my react-native app I want to make a post request to my server, and depending on the result, I want to show a message. I'd like to unit-test this using jest, mocking away the call to the backend. I tried to create a minimal example to show what's going on: This is the Component I am testing impor...
konse
1

votes
2

answer
160

Views

How to mock System.in in Java (except using inside Junit Test Case)?

I have used TextFromStandardInputStream with JUnit Test Case, which works fine. But now I want to mock StandardInputStream outside Test Cases for my requirements. I have used the same TextFromStandardInputStream outside the Test Case but it didn't work at all. So, is there any way to do the work don...
Nalin Adhikari
1

votes
1

answer
84

Views

Mock function outside package

I'm developing a Django software with different apps on it. I'm testing some views and I want to mock the return of a function inside these views. For example I have this view (located at apps.policies.views): def upload_policy_document(request): # code fragment avoid # save document ot ipfs respo...
Albert Diaz
1

votes
1

answer
577

Views

Mocking a http response in kotlin

Currently I am working on a hobby project with that I want to learn a bit about kotlin. I implemented an object that makes HTTP get requests and returns the Json object from the response. What I'm struggeling with is the mocking of the response or the http framework in my tests. I think if the frame...
fbssn

View additional questions