FAQ Database Discussion Community


How to stub multiple calls to same function to get different returns using minitest

ruby,mocking,minitest,stubbing
I am trying to stub a class method. The method has multiple calls to 'gets'. I wanted to manually return specific values to 'gets' calls. My code is similar to this - ParseAndPlay.stub :gets, {***NEED SOMETHING HERE***} do ParseAndPlay.run end and ParseAndPlay.run expects def ParseAndPlay.run gets #=> expects "5 5"...

AngularJS Unit Testing - multiple mocks and providers

javascript,angularjs,unit-testing,mocking
I'm starting to do unit testing for my Angular app, and I had some questions on how to actually structure the tests folder. I basically used the yeoman angular generator, so it comes with Jasmine and Karma pre-configured. Here's a scenario of what I'm trying to test... I have a...

Injecting dependency with Guice in non-constructor method

java,mocking,tdd,guice,roboguice
I'm working on a component that creates HTTP requests dynamically, and I'd like to be able to mock those requests for unit testing. Currently the implementation looks something like this: class ModelClass { public void populate() { HTTPRequest request = new HTTPRequest(); //configure request... request.send(); } } Is there a...

Python mock testing process with retry logic. Creating different mock in each retry

python,git,unit-testing,mocking
Background: I am trying to test my wrapper class for git. This class does things like retry git commands when they hang or fail (Our repos are huge). I can mock git with something like mockproc - https://pypi.python.org/pypi/MockProc/ The problem I am facing is how to test retry logic, Ideally...

Mocked repository does not trigger as expected

spring,unit-testing,mocking,mockito,mockmvc
I have a Controller Unit test using Mockito and MockMvc. After a POST request, the POSTed object is resolved correctly, but my repository mock is not triggered. Here is the mock code: Date mydate = new Date(); Notification not = new Notification(); not.setId(-1L); not.setUserid("BaBlubb"); not.setTimestamp(mydate); not.setContent("MyContent"); Notification not2 = new...

Nsubstitute, changing the value of a property which is substituted

c#,unit-testing,mocking,xunit,nsubstitute
I would like to mock a property in my model to a specific value (because it has a private setter). Then I would call a method which changing this property and then check result. The problem is that the property would always return this value. Can I somehow get around...

OCMock test category methods

ios,unit-testing,mocking,ocmock
I may not completely understand mocking as I have a burning question about a very basic scenario. How does one test an instance method of a class OR how does one test a category method for a class? Consider a class PeerMessage which defines a few properties, etc. I create...

Where to store a binary file to be used for unit testing

java,unit-testing,resources,mocking,directory-structure
Where should I store a resource (binary file in my case) that I need to use for unit testing? Specifically, my directory structure is a standard: src -> main -> java -> com.company.project -> classes... -> test -> java -> com.company.project -> classes... I want to mock a file being...

How to mock a redis client in Python?

python,unit-testing,mocking,python-mock
I just found that a bunch of unit tests are failing, due a developer hasn't mocked out the dependency to a redis client within the test. I'm trying to give a hand in this matter but have difficulties myself. The method writes to a redis client: redis_client = get_redis_client() redis_client.set('temp-facility-data',...

mock doesn't work in objects on kwargs

python,mocking
It seems that the kwarg assignment is not getting mocked in the mock.patch, but if it's called inside a function, it is. Any ideas? import platform import mock def test(arch=platform.machine()): print "arch = %s" % arch print "machine = %s" % platform.machine() with mock.patch.object(platform, "machine", return_value="TEST"): test() # This outputs...

How can I expect that a certain method is called with a specific block?

ruby-on-rails,ruby,rspec,mocking
I want to be able to test with rspec that a specific gem called with a specific block: The code looks like this SomeGem.configure do |config| config.username = "hello" config.password = "world" end and the spec that I have written looks like this: it 'sets valid gem configuration' do credentials...

Stubbing a method in php

php,mocking,phpunit,stubbing
I have an issue where I don't know how to say, when x is called, it expects y to be called at least once and I don't care what y does, so long as its called. So if we look at this example: public static function createAction($params) { $postParams =...

Rspec testing find_or_create method

ruby-on-rails,rspec,mocking,simplecov
I've checked my simplecov result and I've seen that record = User.where("fb_id = ? or email = ? ", params[:fb_id], params[:email]).first_or_create do |rows| rows.first_name = params[:first_name] rows.last_name = params[:first_name] etc(all the variables after do |rows| ) haven't covered. Any ideas, how could I test this stuff ? ...

Minitest::Mock and case statements

ruby,mocking,minitest
Any idea why the following code does not work? require 'minitest/mock' test = Minitest::Mock.new test.expect :class, Class p case test when Class 'class' else 'nope' end # => 'nope' … but should return 'class' p test.class === Class # => true ...

How to unit test Clob conversion to String?

java,unit-testing,junit,mocking
This simple method returns all the content of a Clob retrieved from the database as String. How can I test/mock it properly, guaranteeing it will always return the full content of the Clob argument (assuming its size will not be higher than an Integer)? import java.sql.Clob; public class ClobUtils {...

How to mock web service call without passing mocked class as parameter

web-services,junit,mocking
I have a web serivce class which need to unit tested. Here is class which is under test public class ValidatePaymentMessage { public CsmValidationResultX validatePaymentmsg(String csmName, String base64PayloadXML){ //Call Web Service to validate Payment CsmValidationResultX responseMsg=null; PaymentManagerWebService paymentManagerWebService = new PaymentManagerWebService(); PaymentManagerWebServiceImpl serviceAddrs = paymentManagerWebService.getPaymentManagerWebServicePort(); try { responseMsg = serviceAddrs.validatePayment(csmName,...

Autowired MessageSource null in @ControllerAdvice unit testing controller

spring,unit-testing,mocking,spring-boot,mockito
I have added the setHandlerExceptionResovlers to my builder and that works well except the exceptionhandler bean has autowired MessageSource and when unit testing this is null. I assume it might be cause of having to manually setup the exception handler in test. The flow is calling the controller with invalid...

Moq SignalR Client events

testing,mocking,signalr
I have a service that uses the SignalR .Net Client to communicate with the server, and I want to add some test to check how the client will react to connection problems (Slow-Internet, Intermittent Connection, No connection at all), the problem is that I don´t know how to mock this...

Rhino mocks calloriginalmethod call is obsolete

c#,unit-testing,mocking,rhino-mocks
I'm writing a unit test code for a GameBoard object that's part of a project to make the card game "Dominion" in C#. I'm using rhino mocks to test a method that runs a while(! GameIsOver). Inside, the next player is gotten, then called on to take their turn. A...

python class method mocking failure

python,flask,mocking,patch
Trying to understand mocking/patching and I have a restful API project with three files (FYI, I'm using flask) class1.py domain.py test_domain.py class1.py file content: class one: def addition(self): return 4+5 domain.py file content: from class1 import one class DomainClass(Resource): def post(self): test1 = one() val = test1.addition() return {'test' :...

How do I write to and read from a mocked file object in python, with mock?

python,unit-testing,mocking
I'm trying to write a string to a mocked file object in the python mock library, but it turns out that my method of writing to the mock object does not persist anything, even in memory, it seems. I'm trying like this in the ipython shell: In [1]: import mock...

Tests repeats the code with Mockito

java,unit-testing,junit,mocking,mockito
My tests just repeats the code. For method public void start(Context context) { context.setA(CONST_A); context.setB(CONST_B); ... } I wrote test using Mockito @Test public void testStart() throws Exception { Context mockContext = mock(Context.class); action.start(mockContext); verify(mockAction).setA(Action.CONST_A); verify(mockAction).setB(Action.CONST_B); ... } Or for public void act() { state.act(); } test @Test public...

Why isnt mockito injecting the right response?

java,unit-testing,mocking,testng,mockito
I'm trying to use mockito in the following manner. Here's a part of main class IClient. public LoginResponse doLogin() { WebTarget target = buildTarget(); MultivaluedMap<String, Object> authHeaders = prepareHeaders(); Builder buildRequest = buildRequest(authHeaders,target); Response loginRsp = buildRequest .post(Entity.entity(" Valid JSON string", MediaType.APPLICATION_JSON_TYPE)); if(loginRsp == null) LOGGER.error("Response was null");// Response is...

Mockery mock method inside closure

unit-testing,laravel-4,mocking,phpunit,mockery
I have problem unit testing method inside closure called by call_user_func() example : public function trans($lang, $callback) { $this->sitepress->switch_lang($lang); call_user_func($callback); } on controller : public function sendMail() { $foo = $baz = 'something'; $mail = $this->mailer; $this->helper->trans_c('en', function() use($foo, $baz, $mail) { $mail->send('Subject', $foo, $baz); }); } test case :...

How to check JSON in response body with mockMvc

java,spring,junit,mocking,spring-test-mvc
This is my method inside my controller which is annotated by @Controller @RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8") @ResponseBody public JSONObject getServerAlertFilters(@PathVariable String serverName) { JSONObject json = new JSONObject(); List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, ""); JSONArray jsonArray = new JSONArray(); jsonArray.addAll(filteredAlerts); json.put(SelfServiceConstants.DATA, jsonArray); return json; } I am expecting...

How can I test through a mocked promise with Mocha?

node.js,unit-testing,mocking,promise,mocha
My node.js code is: function getPatientNotificationNumbers(patientId) { patientId = patientId && patientId.toString(); var sql = "SELECT * FROM [notification_phone_number] "; sql += "WHERE patient_id = " + escapeSql(patientId); return sqlServer.query(sql).then(function(results) { var phoneNumbers = _.map(results[0], function (result) { var obj = { id: result.id, phoneNumber: result.phone_number, isPrimary: result.is_primary, isVerified: result.is_verified,...

How to unit test Java Hbase API

java,hadoop,mocking,hbase,storm
I am using the Java HBase API to get a value from Hbase. This is my code. public class GetViewFromHbaseBolt extends BaseBasicBolt { private HTable table; private String zkQuorum; private String zkClientPort; private String tableName; public GetViewFromHbaseBolt(String table, String zkQuorum, String zkClientPort) { this.tableName = table; this.zkQuorum = zkQuorum; this.zkClientPort...

How to capture field value when a method of a class is called in Python?

python,unit-testing,mocking
I have a weird 3rd party library that requires me doing the following (A is imported from that library): def foo(my_props): a = A() a.props = my_props a.post() So what I want is to make sure that when a.post() is called, its props are set correctly. Note that this is...

Argument 1 passed to Foo::__construct() must be an instance of Psr\Log\LoggerTrait, instance of Mock_Trait_LoggerTrait_65811a25_bdddd884 given

php,unit-testing,mocking,phpunit,trait
I'm trying to mock a simple trait with PHPUnit but it is resulting on a FatalError, it works if I remove the type hinting: Argument 1 passed to Foo::__construct() must be an instance of Psr\Log\LoggerTrait, instance of Mock_Trait_LoggerTrait_65811a25_bdddd884 given The class: use Psr\Log\LoggerTrait; class Foo { /** * @var LoggerTrait...

How to let MagicMock behave like a dict?

python,mocking
mock(http://mock.readthedocs.org/en/latest/index.html) is a great tool in python for unit test. It can conveniently mock a method or class or dict.But I encountered a problem which I couldn't find a straightforward way to deal with by mock. This is the function to be tested: def function_to_be_tested(id, responses): if not id in...

Python: Mock doesn't work inside celery task [duplicate]

python,django,unit-testing,mocking,celery
This question already has an answer here: Why python mock patch doesn't work? 1 answer I want to use python mock library for testing that my Django application sends email. Test code: # tests.py from django.test import TestCase class MyTestCase(TestCase): @mock.patch('django.core.mail.mail_managers') def test_canceled_wo_claiming(self, mocked_mail_managers): client = Client() client.get('/') print(mocked_mail_managers.called)...

Reusing angular mocks in Jasmine tests using $provide

angularjs,testing,mocking,jasmine,karma-runner
I wish to reuse my mocks instead of having to set them up in every unit test that has them as dependency. But I'm having a hard time figuring out how to inject them properly. Here's my attempt at unit test setup, which of course fails because ConfigServiceMockProvider doesn't exist....

random.choice gives different results on Python 2 and 3

python,random,mocking
Background I want to test my code which depends on random module. The problematic PR is https://github.com/Axelrod-Python/Axelrod/pull/202 and code is here https://github.com/Axelrod-Python/Axelrod/blob/master/axelrod/strategies/qlearner.py The problem Since random module produces pseudo-random numbers, I always set random.seed(X) to known value X. This works for consecutive test runs. However, Python 3 seems to give...

Mockito: How to test if another class' method is called within a method of a Mock?

junit,mocking,mockito,jboss-arquillian,verify
So I have a service class. public class OrganisationService { public List<Organisation> findAllForeignOrganisations() { // a few rows of JPQL-code that searches the database return myCriteria.getResultList(); } //...Other methods that return Lists with other types of organisations... } Then I have a class which I want to test. What I...

ActiveRecord: Mock has_many relation call

ruby-on-rails,activerecord,rspec,mocking
I'm fairly new to testing, so I've been struggling with using the correct syntax, especially regarding mocks. I want to test my destroy action in cars_controller.rb def destroy if current_user.cars.exists?(params[:id]) car = current_user.cars.find(params[:id]) # only destroy the car if it has no bookings car.destroy unless car.bookings.exists? end redirect_to user_cars_path(current_user) end...

Mocking stored procedure's output parameter

c#,.net,unit-testing,mocking,moq
I have following method public bool IsUserAllowedToDoThings(string userName, string thingToDo) { var outputParameter = new ObjectParameter("IsAllowed", typeof(bool?)); _context.SP_IsUserAllowedToDoThings(userName, thingToDo, outputParameter); return (bool)outputParameter.Value; } The method just calls SP using EF and return SP's output result. But I'm having problems to mock SP's output for unit testing. P.S. I'm using MOQ...

Mocking or not registry-like object in phpunit tests

unit-testing,mocking,phpunit
I'm facing some difficulties to mock a registry-like object in my tests, this might be because of a wrong design but it always end using $this->at(x) and, IMHO, therefore tightly coupling my test with tested code. For example, my registry-like object looks like something like this ( remember that its...

jUnit change behavior of a method

java,junit,mocking,powermock
I have to make some jUnit tests for some methods and I can't change the source code. Is there any possibility to change the behavior of a function without change source code? Look a straight-forward example: Class A and B are source code (can't change them). I want to change...

JMockit: Overriding @Mocked class

java,unit-testing,mocking,jmockit
I have an internal StreamGobbler class that has 7 methods in it. I'm looking for a quick way to mock all the methods by default, but override one method named getOutput() (e.g. Partial Mocking). (full code not shown for clarity) public class StreamGobbler extends Thread { public String getOutput() public...

How to mock a Android NFC Tag object for unit testing

android,unit-testing,android-intent,mocking,nfc
I'm currently working on an Android project which needs NFC integration. Now I want to write some (j)unit tests to see if the application can receive NFC intents (specifically ACTION_TECH_DISCOVERED) and put the given tag (in NfcAdapter.EXTRA_TAG) on a bus system. However to my surprise I cannot create a Tag...

How to stub CocoaLumberjack or NSLog with OCMockito

ios,objective-c,unit-testing,mocking,ocmockito
I can stub/verify a class method, but I'm having difficulty with defined macros. I'm trying to test that one of my methods calls DDLogInfo. It's defined like so in the CocoaLumberjack source #define DDLogInfo(frmt, ...) LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagInfo, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) thanks!...

how to mock function call used by imported pypi library in python

python,unit-testing,mocking
I have the following code that I'm trying to test: great_report.py from retry import retry @retry((ReportNotReadyException), tries=3, delay=10, backoff=3) def get_link(self): report_link = _get_report_link_from_3rd_party(params) if report_link: return report_link else: stats.count("report_not_ready", 1) raise ReportNotReadyException I've got my testing function which mocks _get_report_link_from_3rd_party which tests everything but I don't want this function...

How could I Mock this code?

c#,unit-testing,mocking,nunit,moq
I want to start mocking some code but I am unsure how to do it. I have read a few tutorials but I cannot apply it to my code (There maybe a reason behind it). I am using NUnit and Moq. (I have removed all other methods so I can...

Changing the second result of a function call with mock

python,mocking,py.test,python-mock
I have a loop that looks like this: for i in range(len(some_list)): response = requests.post(some_url, some_params) if response.status_code != HTTPOk: # do something What I would like to do is change response of requests.post in the second iteration of the loop. From within my test, I know I can do...

How to stub a class method using rspec/rspec-mocks

ruby,rspec,mocking
I am using rspec-mock for test-driven-development. I am starting implementing a single class and mocking/stubbing the other classes using rspec-mock. Mocking objects of classes yet to be implemented works well. However when I try to mock a class method of a class that does not exist yet, I haven't been...

angular switch from test ng-app to dev ng-app

angularjs,mocking,protractor
So here is my problem I want to mock my data when I run tests or am offline but call the extarnal API when I can/want by using somthing like npm run protractor and npm run protractor-mock. the solution I have cobbled together is having 2 index.html files one with...

Jasmine - correctly mocking an object with a constructor

javascript,angularjs,unit-testing,mocking,jasmine
I'm trying to mock the native WebSocket in a jasmine test for Angular, I can spy on the constructor and send function, but I can't figure out how to spoof a call of onmessage. WebSocket is extracted to an Angular constant: webSocket. My test looks like this: describe('Data Service', function...

jMockit - How make constructor invocation to return a mock

java,mocking,testng,jmockit
We are currently using Mockito + PowerMock as our main mocking framework and had a few issues with this once started moving some of our code to java 8. Because of this we decided to evaluate jMockit as an alternative. I have quite a good understanding of mocking concepts but...

can't inject Providers mock in JerseyTest

java,mocking,jersey,integration-testing,inject
I'm getting Providers from context in my filter to get defined ObjectMapper public class Filter implements ContainerRequestFilter, ContainerResponseFilter { @Context private Providers providers; @Context private HttpServletRequest request; private ObjectMapper getObjectMapper() { ContextResolver<ObjectMapper> contextResolver = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE); if (contextResolver == null) { return new ObjectMapper(); } return contextResolver.getContext(null); } } but...

PHPunit expectation on Mock object is not fulfilled

php,mocking,phpunit,expectations
Here is my class: public function __construct(Manager $moduleManager, Source\Yesno $yesNo) { $this->moduleManager = $moduleManager; $this->yesNo = $yesNo; } public function my1() { $this->moduleManager->isOutputEnabled(''); $this->yesNo->toOptionArray(); } public function my2() { $this->moduleManager->isOutputEnabled(''); $this->yesNo->toOptionArray(); } Here is my test: ... $this->observerMock = $this->getMock( 'path\to\Observer', null, [$this->moduleManagerMock, $this->yesNoMock], '', true ); ......

Can I monkey-patch dependencies when writing TypeScript unit tests

javascript,unit-testing,mocking,typescript,monkeypatching
Our Web application has a very rich Javascript front-end, with a large number of custom widgets, wizards etc. We're looking at migrating some of it (perhaps eventually all) to TypeScript primarily for the benefits of easier refactoring/fewer bugs. We've got JavaScript unit tests for widgets/client-side business logic - which we...

How to check that method of a mockobject was not called only with a specific parameter?

php,unit-testing,mocking,phpunit
I have a PHPUnit_Framework_MockObject_MockObject of a Logger. In a unit test, I do not want a call to the warn method to happen with a specific string parameter doNotCallMeWithThisString. I have come this far: public function testThis() { ... $logger = $this->getMockLogger(); $logger->expects($this->exactly(0))->method('warn')->with( $this->equalTo('doNotCallMeWithThisString') ); ... } Yet this fails...

Is there a way to tell Autofixture to only set properties with a specific attribute?

c#,unit-testing,dependency-injection,mocking,autofixture
I use Unity for dependency injection, and in a few places I use property injection (with the [Dependency] attribute) rather than constructor injection. I'd like to use AutoFixture as a mocking container for my unit tests, but by default it sets all public properties on the system under test. I...

Python: using Mock to override class method

python,mocking,python-unittest
There a FooObject class with only one version field and one update() method. class FooObject(models.Model): version = models.CharField(max_length=100) I would like to override update method for the unittest using Python's Mock tool. How would I do it? Should I use patch for it? foo_object.update = Mock(self.version = '123') ...

Mocking db queries with querydsl - issue with Optional

java,junit,mocking,guava,querydsl
I've some difficulties to write tests on DB queries for my application, which uses querydsl on top of a mongo. I've found several examples of people who just unit-test the query object itself, but I'd like to go a step further and test how the query performs (like an integration...

Unable to mock __subclasses__ in python

python,mocking
Why does the following code not work? >>> from mock import * >>> class A(object): ... pass ... >>> mock = create_autospec(A) >>> mock.foo = Mock() # this works >>> mock.__bar__ = Mock() # this works too >>> mock.__subclasses__ = Mock() # this fails AttributeError: Mock object has no attribute...

mocking findOneBy“field” in doctrine2 with phpunit

php,unit-testing,doctrine2,mocking,phpunit
If I mock the repository method find I get the expected results, but if I cal either findBy, findOneBy, findOneById I always get null. example: $mock->expects($this->once()) ->method('getId') ->will($this->returnValue(1)); $mockRepository->expects($this->any()) ->method('findBy') //if here I use 'find' works for all other cases always null ->will($this->returnValue($mock)); Is there a reason why this happen?...

Generator returning Mocks that fail assert_called_with

python,unit-testing,testing,mocking
I'm trying to test a script that is organized like this: class Processor(object): def __init__(self, *args): pass def my_iterator(elements): for element in elements: yield Processor(element) I just want to test that a Processor object was created using each element in the iterable that was passed to my_iterator(). I'm testing Processor...

Handling parameterized calls in Rhino Mocks

c#,mocking,rhino-mocks
I have a mailer class, it has a "SendMessage" method that needs an object implementing an interface IEMailConfiguration. I wanted to mock the mailer so that it does not send the mail but instead just adds the given mail configuration object to a list. This is what i got so...

Python Mocking of Boolean Function

python,django,python-2.7,unit-testing,mocking
So I have just begun working with the mock library to perform some unit testing. But ran across a problem that is certainly mysterious to me. When I call the below code stream.open() always evaluates to True, as it seems to be returning the Mock object rather than the False...

Mocking (in java) with object tree / net

java,unit-testing,mocking,integration-testing
Theoretical scenario: We have an interface implemented using spring batch, which when triggered fetches a complicated object tree from a service. The type of service is not relevant, it is a pojo and return normal objects. It is transformed into our domain model and then using certain business logic calculations...

Python mock error: stop called on unstarted patcher

python,unit-testing,mocking
I have a function let's say def temp.i am mocking it the following way: msg = "Mocked!!!!!!!" @mock.patch.object(Someothermodule.Someclass,'Somefunction',create=True,side_effect=Error(Error.something,msg)) def temp(self,mock_A): Its a huge project so cant post the details here.But what's happening is the function temp does get mocked and i do get the correct message but later on i...

Mocking a method outside of a class

python,unit-testing,mocking,wsgi,assert
I need to write a unit test for credential checking module looks something like below. I apologize I cannot copy the exact code.. but I tried my best to simplify as an example. I want to patch methodA so it returns False as a return value and test MyClass to...

Mocking assert_called_with in Python

python,unit-testing,mocking
I'm having some trouble understanding why the following code does not pass: test.py import mock import unittest from foo import Foo class TestFoo(unittest.TestCase): @mock.patch('foo.Bar') def test_foo_add(self, Bar): foo = Foo() foo.add(2, 2) Bar.add.assert_called_with(2, 2) if __name__ == '__main__': unittest.main() foo.py from bar import Bar class Foo(object): def add(self, x, y):...

Testing a redirect outside of a controller

ruby-on-rails,rspec,mocking
I have a helper module with a method that fires off redirect_to if the current user does not have permission to visit a web page. I am getting a NoMethodError error when running the tests, since the helper does not actually have a redirect_to method. I have tried stubbing out...

Scala unit testing - stubbing a singleton

scala,unit-testing,mocking
I'm new to unit testing in Scala and I can't find a way to stub a function defined in a singleton object. For example: class Profile { def getLatest ... Feed.getLatestEntries ... } object Feed { def getLatestEntries: Future[List[FeedEntry]] { /* Access some API*/ } } I'm trying to unit...

PHPunit call magic methods

methods,mocking,phpunit,magic-methods
I have magic method getData. Is it possible to call following inside unit test: $this->attributeMock ->method('getData') ->with('additional_data') ->willReturn('some value'); $this->attributeMock ->method('getData') ->with('is_default') ->willReturn('something'); When I do this, I got: Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'is_default' +'additional_data' Is there some another way?...

Angular and Jasmine: how to mock a service that returns a promise

javascript,angularjs,unit-testing,mocking,jasmine
I have the following controller in AngularJS that is invoking a service provided by "$mdSidenav" from Angular Material. This is service is provided by a factory method. angular.module('leopDirective', []) .controller('MenuCtrl', function ($scope,$timeout,$mdSidenav,$log) { $scope.mdSidenav = $mdSidenav; $scope.close = function () { $mdSidenav('left').close().then(function() {$scope.closed=true; }); }; }); I am trying to...

Can an abstract class be mocked using mockito?

unit-testing,junit,mocking,mockito,abstract-class
In a class under test, if its constructor takes in an abstract class parameter can we mock it using mockito? Ex public abstract AbstractClass{ } //Class under test public class SourceClass{ SourceClass(AbstractClass abstractClass){} } @RunWith(MockitoJUnitRunner.class public SourceClassTest{ @Mock AbstractClass abstractClass; } whenever I do this i get this error java.lang.ExceptionInInitializerError...

How can I unit test node.js functions with Mocha?

node.js,unit-testing,mocking,mocha
I am trying to test a function that looks like: function sendVerifySms(patientId, data) { var smsNumber = data.smsNumber; var verifyCode = ((Math.random() * 1000000) | 0).toString(); var sql = "UPDATE [patient]"; sql += " SET phone_sms_verify_code = '" + verifyCode + "',"; // verification must take place within a one...

Mocking/Unittesting when using Node serialport callbacks

javascript,node.js,unit-testing,mocking
I am working on a web-interface for a 3rd party device that connects via serial port. Example code below... var serialport = require("serialport"); var SerialPort = serialport.SerialPort; var sp = new SerialPort("/dev/ttyACM0", { parser: serialport.parsers.readline("\n") }); sp.on("data", function (rawData) { ... My question is how can I mock/Unittest the sp...

Alternatives to mock an static method

java,junit,static,mocking,mockito
I am developing a desktop application, I want to test the method foo of MyClass and I have the following scenario: MyClass: import package.MainWindow; public class MyClass{ public int foo(){ //some logic // . . . boolean result = getResult(); if (result) { MainWindow.printInMain("Success"); return 1; } else { MainWindow.printInMain("Fail:...

How to use mocking in this case?

unit-testing,mocking
Here is my problem: This is the method for which i am trying to write test case. This method trying to create instance of "HttpClient" but this server is not available on my side. So i am trying to achieve this by using mocking, But i am not successful in...

Test a void method with conditioned loop using mockito

java,unit-testing,junit,mocking,mockito
I have following method which asks for user input until valid user credentials are entered.It then generates id for that user and sets registered =TRUE. 1.How can I check the value of local variable "registered" from my unit test? 2.How can I assert in my test that while loop executed...

How to mock asyncio coroutines?

python,unit-testing,mocking,python-asyncio
The following code fails with TypeError: 'Mock' object is not iterable in ImBeingTested.i_call_other_coroutines because I've replaced ImGoingToBeMocked by a Mock object. How can I mock coroutines? class ImGoingToBeMocked: @asyncio.coroutine def yeah_im_not_going_to_run(self): yield from asyncio.sleep(1) return "sup" class ImBeingTested: def __init__(self, hidude): self.hidude = hidude @asyncio.coroutine def i_call_other_coroutines(self): return (yield from...

Junit VerificationModeFactory.times() vs mockito.times()

junit,mocking,verify
What is the difference between VerificationModeFactory.times() and mockito.times()?

Mocked Class & Asserting Method Calls

python,unit-testing,mocking
Stumped on how to mock a class and be able to assert that its' methods are called with some arguments. When I assert the call i get a "Not called" assertion but, I can see the method call in the mock_calls attribute. sandbox/module.py class Subject(object): def __init__(self): pass def run(self,...

Python unittest mock an API key

python,mocking,api-key,python-unittest
I'm writing unit tests for the Client class of client.py, which queries an API. Each test instantiates the client with c = client.Client("apikey"). Running one test at a time works fine, but running them all (e.g. with py.test) I get a 401: "Exception: Response 401: Unauthorized Access. Requests must contain...

Can I configure Unity to automatically return a fake for interfaces that are not registered?

c#,unit-testing,dependency-injection,mocking,unity
I'm a bit tired of manually registering fake dependencies in my unit tests... I'm wondering if there is a way to configure Unity in such a way that, if there is no registered implementation for a given type, it automatically creates a fake using FakeItEasy or some other mocking framework....

How to access object instance from mocked instance method when unit testing?

python,unit-testing,mocking
In the code below where it says foo_obj = ????, how can I get a reference to the Foo object instance, or what could be a better approach? 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): foo_obj = ????...

How I can write mockito junit for Listener class

java,spring,junit,mocking,mockito
Hi how to write mockitJunit for public void contextInitialized(ServletContextEvent event) in below class. public class AppStartUpContextListener extends ContextLoaderListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { } @Override public void contextInitialized(ServletContextEvent event) { final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); final Configuration appConfig = (Configuration)...

Exception not called when using side_effect with mock

python,mocking,python-mock
I have a function in a class called "my_class" in a module called "my_module" that contains this snippet: try: response = self.make_request_response(requests.post, data, endpoint_path) except requests.exceptions.HTTPError as err: if err.response.status_code == requests.codes.conflict: logging.info('Conflict error') And I'm trying to test it like so: error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found') mock_bad = mock.Mock(side_effect=error)...

How to include private contructor in Line Coverage?

java,unit-testing,mocking,cobertura,jmockit
I am using jmockit to mock my classes for unit test purpose. Everything is working fine so far. I have a factory which is thread safe and singleton as shown below: So for below class, I am able to get 50% Line Coverage because I am not able to cover...

Unit testing a fluent interface with Mockito

java,unit-testing,mocking,mockito,builder-pattern
I want to mock the DAO interface used in the builder pattern as shown below. However when I run the test below it passes indicating that my mock object is never called. What am I doing wrong? public class DBContent { ... public static class Builder { DAO dao =...

Mockito rule not being applied

java,unit-testing,junit,mocking,mockito
I was writing a testcase using Mockito and it seems to me one Mockito rules does not get defined. Below is my scenario. public class DummyTest { private final String[] alphabet= {"a", "b", "c", "d", "e" }; private final String[] numeric= {"1", "2", "3", "4", "5" }; AtomicInteger idx; String...

Using mock to patch a non-existing attribute

python,unit-testing,testing,mocking,py.test
I'm trying to test a context manager that makes use of a class that uses some __getattr__ magic to resolve several attributes which don't actually exist on the class. I'm running into a problem where mock is raising an AttributeError when trying to patch the class. Simplified example of objects...

How to call mocked method in Python mock

python,unit-testing,mocking,python-mock
I want to create a mock method that calls the underlying method being mocked. I'm imagining something like the following, but I can't find any documentation about the mock object holding a reference to the object being mocked, which I've denoted as [[wrapped_method_foo]] below: from mock import patch class Foo(object):...

Mock user input()

python,testing,input,mocking,flexmock
I am trying to simulate user input for a python script that I have going using py.test. Here's some basic code that represents what I'm trying to accomplish: def ask(): while True: age = input("Enter your age: ") if int(age) < 13: print("You are too young") else: name = input("Enter...

NSubstitute: When…Do not working while mocking void method

c#,mocking,nsubstitute
I am new to NSubtitute and really confused why below test case is failing. public class IFoo { public void SayHello(string to) { Console.writeLine("Method called"); } } [Test] public void SayHello() { var counter = 0; var foo = Substitute.For<IFoo>(); foo.When(x => x.SayHello("World")) .Do(x => counter++); foo.SayHello("World"); foo.SayHello("World"); Assert.AreEqual(2, counter);...

Python mock access “real” objects while mocking a module

python,mocking,python-mock
Is it possible to access "real" objects while mocking a module? What I'm trying to do is mock some function, but throw "real" exceptions, like this: @mock.patch('my_project.requests') def test_foo(self, mock_requests): mock_requests.post = mock.Mock(side_effect=requests.ConnectionError()) thread = CommandThread("command", 3, 2, 0) thread.run() #this is were I exercise requests.post self.assert(thread.was_successful is False) Inside...

python cross platform testing: mocking os.name

python,testing,mocking,nose
what is the correct way to mock os.name? I am trying to unittest some cross-platform code that uses os.name to build platform-appropriate strings. I am running on a Windows machine but want to test code that can run on either posix or windows. I've tried: production_code.py from os import name...

Nsubstitute Calls Method in When even though there is DoNotCallBase

c#,unit-testing,mocking,nunit,nsubstitute
I am partially mocking a class that has these two methods: public void EmitTo(string connectionId, ChatMessage message) { Clients.Client(connectionId).broadcastMessage(message.User.UserName, message.Message); } public virtual void Broadcast(ChatMessage message) { Clients.All.broadcastMessage(message.User.UserName, message.Message); } In my test [SetUp] I have these calls: hub = Substitute.ForPartsOf<ChatHub>(myMockedClient, context, groupManager); hub.When(x => x.Broadcast(Arg.Any<ChatMessage>())).DoNotCallBase(); hub.When(x...

`answers` is not invoked when mocking a method with `call-by-name` parameter

mocking,mockito,specs2,callbyname
There is a class InvokeLater, the definition is like: class InvokeLater { def apply(f: => Any): Unit = { // do something ... f // do some other thing } } In specs test, I mocking it like: val invokeLater = mock[InvokeLater] invokeLater.apply(any) answers { f => f:Unit } But...

NSubstitute mock a void method with out parameters

c#,unit-testing,testing,mocking,nsubstitute
I am new to NSubstitute, I am trying to mock a void method with 2 out parameters and I am pretty sure I am doing it wrong. I have a CustomerDataAccess class that has a method with the following signature: void GetCustomerWithAddresses(int customerId, out List<Customer> customers, out List<Address> addresses); The...

Is it possible to use Mockito in Kotlin?

java,mocking,mockito,kotlin
The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown. `when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse } Mocked method: public open fun login(userCredentials: UserCredentials): Response ...

ReturnForAnyArgs without using NSubstitute

mocking,asp.net-identity,owin,nsubstitute
I am unit testing a Post method that in its implementation uses a Microsoft.AspNet.Identity.Owin.SignInManager because SignInManager inherit from a class and not an interface I cannot use NSubstitute to mock the SignInManager object. Therefore I cannot use the ReturnForAnyArgs method to get it to return a SignInStatus of say Success....

Stub/mock process.platform sinon

variables,mocking,stub,sinon
I am working with process.platform and want to stub that string value to fake different OSes. (this object is generated out of my reach, and I need to test against different values it can take on) Is it possible to stub/fake this value? I have tried the following without any...

Is there any way to get all data retrieved between two points in C# code (Linq-to-sql)

c#,asp.net,unit-testing,linq-to-sql,mocking
My cenario is the follow: I'm working in one system developed in C# Asp.Net (a big, huge and definetly grown anyway system). And I'm trying to begin create some unit tests to start refactor (believe, it's need refactor (there some controllers with 10k, 12k lines). The problem is that a...

How to mock http.Head()

unit-testing,go,mocking
I'm studying the outyet example project from https://github.com/golang/example/tree/master/outyet. The test file does not cover the case where http.Head(url) returns an error. I would like to extend the unit tests to cover the if statement where the error is logged (https://github.com/golang/example/blob/master/outyet/main.go#L100). I would like to mock http.Head(), but I'm not sure...

Spock verifying an exception thrown by mock together with mock interaction

groovy,mocking,spock
The problem I encountered is when I try to verify in the then block that an exception has been thrown, and that call on a mock has been made. Look at the setup below: class B { def b(A a) { a.a() } } class A { def a() {...