mardi 30 juin 2015

Django Response has no content - How to debug?

I am trying to add testing to my Django 1.8 application and am running into trouble with a test to make sure registration goes through successfully. I don't know how to debug to see what is wrong.

I make the following call in my code after setting up the Client.

class LoginTests(TestCase):
    def setUp(self):
        self.client = Client()

    def test_user_can_select_vegetarian_on_account_create(self):

        data = {'username': 'TestUser', 'password1':'pass', 'password2':'pass', 'email':'bad@email.com', 'is_admin':True}
        r = self.client.post('/register/', data)
        print(r.content)
        self.assertTrue(r.context is not None)
    print(list(User.objects.all()))

the print(r.content) just prints a blank, so nothing is coming back, although it is a response. When I look at the status code, I get a 302.

I am not sure how to see what is going wrong, so mostly I am just looking at how to debug this process. Print statements in the server code are not showing up so I am totally lost as to what is happening. Any ideas?

Launching jnlp with jfcunit and automating it

Is there a way to launch a jnlp applcation with jfcunit in its setUp() and run test cases on the opened Web start application through the jfcunit?

The jfcunit runs fine with a swing application locally on my PC,but I don't know if it works for a jnlp application.To brief the task that I'm supposed to accomplish,it is-"Automate a JNLP Application in the backend".

Is there any handy method to enumerate and invoke tests of a XCTestCase class in Xcode?

There is a class which provides a set of initXXX methods and some functional methods. It is handy to invoke all the functional tests at runtime when verifying the instance created by all these initXXX methods.

Just like this:

-(void) testEverythingWithInitXXX {
   if ( test of self.tests not postfix by 'WithInit.*' ) {
      invoke it.
   }
}

It is always possible by inspecting the ObjC object at runtime, I'm just wondering if Apple provided any help already in XCTest framework?

Angular JS unit test for web-service response without mocking

I'm making a unit test for angular js application in Karma.

There is a part where my controller function makes a web-service call to the server. I would like to verify the response data from the server side using unit testing.

I have looked at many tutorials. However, they are suggesting to make an angular mock service call to achieve this.

I wonder these mock service calls don't make any actual calls to the server. Instead, they are using sample response data, which is hard coded in unit test code.

I would like to unit test the original workflow (make an actual call to the server) instead of getting the responds from hard coded one.

Any help on this is appreciated.

Code: The below is working fine using mocked response data.

Controller

$scope.Login = function () {
  loginService.then(function (loginServiceObj) {
   loginServiceObj.AuthenticateUserLogin($scope.userName, $scope.password).success(function (data) {
    $scope.responseData = data;
    if (data["statusCode"]) {
     $modalInstance.close(data);
    } else {
     $scope.errorMessage = data['errorMessage'];
    }
   }).error(function () {
    $scope.errorMessage = "An error occured while processing!";
   });
  });
 };

Testing Function:

describe("Login Controller Spec", function () {

 beforeEach(module('ui.bootstrap'));
 beforeEach(module('ngStorage'));
 beforeEach(module('serviceModule'));
 beforeEach(module('loginModule'));
 beforeEach(module(‘appModule'));

 beforeEach(inject(function ($rootScope, $controller, $httpBackend, loginService) {
  scope = $rootScope.$new();
  httpBackend = $httpBackend;
  loginService = _loginService_;
  loginController = $controller('loginController', {
   $scope: scope
  });
 }));
it('Making a login request to the server', function () {

   scope.userName = 'sampleuser';
   scope.password = 'password';
     httpBackend.whenPOST('http://localhost/service/login')
      .respond(200, {
       "success": true
      });

     afterEach(function () {
      httpBackend.verifyNoOutstandingExpectation();
      httpBackend.verifyNoOutstandingRequest();
     });

     scope.$apply(function () {
      scope.Login();
     });

   httpBackend.flush();
   expect(scope.responseData.success).toBe(true);

  });
});

scope.responseData is the object that stores the response data in the controller.

Unit Testing: Check whether an internal function was called or not? Using Sinon and Chai

Consider log.js has function:

var function processData()
{
     if(condition)
          dbInsert();
}

var function dbInsert()
{
  // do some insertion
}

Now I want to test that when processData is called whether dbInsert is called or not. This is my test.js. Which fails test on the last one although when I manually check the db there does exist an entry

it('internal function called or not', function() {

    var Data = '{"id":"123","name":"xyz"}';

    var spy = sinon.spy(log, "processData");
    var spy2 = sinon.spy(log, "dbInsert");



    log.processData(Data);                 

    expect(spy.callCount).to.be.equal(1);
    expect(spy2.called).to.be.true;   // returns false .. 

});

How to generate html report for TestNG test cases run in Netbeans?

I think this should be very simple but I can't figure it out. I have read the testng documentation and other stackexchange posts but nothing makes sense to me. They require expertise that I don't have.

I am writing Java TestNG cases in Netbeans. Can someone please describe, very clearly & thoroughly, the explicit steps needed to generate an html test report after running my TestNG test case in netbeans? I know it has something to do with the test-output folder but I don't know where that is, or how to make it.

I am looking for the simplest, bare-bones, default approach.

I think maven &/or ant might be needed - both are fairly foreign to me.

Please don't just post a link or mark this as a duplicate. I've already searched google and this site.

Thank you for your time and patience with this question

adding Angular unit test mid stream

i have created an Angular app with many modules. All without unit test. Now I am developing a new module with several dependencies and injection. I also want want to add unit test. Can I just write tests for this new module without writing tests for dependencies of old modules?

Testing Lib Files in Ruby on Rails

I am developing a parser for a website. Right now, the parser is contained in a file titled input_parser.rb in my /lib directory. Currently, in my test file, which is titled input_parser_test.rb, I have to use the following lines in order for the parser to be loaded correctly:

    $LOAD_PATH.unshift File.expand_path '../../../lib',__FILE__
    require "input_parser"

How can I get Rails to auto load and detect the lib file? I currently have the test file in the test/unit/ directory, but I've tried putting it in test, test/lib, and test/unit/lib, and I still can't get it to auto load the path correctly. I've also check my config files to make sure that I haven't done anything strange to my requires. I'm fresh out of ideas, so any advice would be appreciated.

Difference between these two methods of testing

For testing a Python library, I can do either

python setup.py install
python setup.py test

or

python setup.py build
python setup.py test

I prefer doing it the latter way. What things would I be missing to not go for the first?

NOTE : I'm not choosing first because in that case I think something at permission level goes wrong over Travis-CI. This is the error log

======================================================================
ERROR: Failure: OSError ([Errno 20] Not a directory: '/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/networkx_metis-1.0-py2.7-linux-x86_64.egg/networkx')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/nose/loader.py", line 414, in loadTestsFromName
    addr.filename, addr.module)
  File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/nose/importer.py", line 86, in importFromDir
    if (self.sameModule(old, filename)
  File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/nose/importer.py", line 131, in sameModule
    if _samefile(mod_path, new_path):
  File "/home/travis/virtualenv/python2.7.9/lib/python2.7/posixpath.py", line 162, in samefile
    s1 = os.stat(f1)
OSError: [Errno 20] Not a directory: '/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/networkx_metis-1.0-py2.7-linux-x86_64.egg/networkx'
----------------------------------------------------------------------
Ran 1 test in 0.314s
FAILED (errors=1)
The command "python setup.py test" exited with 1

proper Python/Django doctest file organization and how to run all django tests at once

I am trying to follow a python tests tutorial at http://ift.tt/1CHAHUp. The wording seems vague, but following it I make a tests dir in my project- by mkdir, not starting an app. It has an init file

mainsite/tests/init.py:

from unit_tst import *

import doctst

__test__={
    'Doctest': doctst
}

mainsite/tests/doctst.py:

"""
This is my worthless test.
>>> print "wee"
wee
>>> print False
False
"""    """
This is my worthless test.
>>> print "wee"
wee
>>> print False
False
"""

mainsite/tests/unit_tst.py:

import unittest

class TestBasic(unittest.TestCase):
    "Basic tests"


    def test_basic(self):
        a = 1
        self.assertEqual(1, a)

    def test_basic2(self):
        a = 1
        assert a == 1

    def test_failure(self):
        b = 2
        assert b == 3

if __name__ == '__main__':
    unittest.main()

The wording is very confusing, as the other says to put these test files under the "tests" directory, then proceeds to keep running ./manage.py test differentappname, when it seems ./manage.py test tests makes sense. Either way, in the main folder ./manage.py test tests yields

Ran 0 tests in 0.000s

OK

but running python tests/unit_tst.py from the main directory works.

[me@localhost site]$ python tests/unit_tst.py
..F
======================================================================
FAIL: test_failure (__main__.TestBasic)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/unit_tst.py", line 17, in test_failure
    assert b == 3
AssertionError

----------------------------------------------------------------------
Ran 3 tests in 0.000sscriptcitymirror

My questions are

  1. What is the proper layout for tests? Can all tests for different apps import models from those apps and the test files all live under tests/?

  2. How do you run these tests (why did my command fail)?

Thank you

Is A Mocking Library Redundant If I Already Have a Stub?

Let's say I have the following classes in the respective source folders/packages...

[src/myApp]
|_Employee «concrete»
|_Manager «abstract» 
|_ManagerImpl «concrete» (Class Under Test)
|_Recruiter «abstract» 
|_RecruiterImpl «concrete» (Collaborator)

...

public class ManagerImpl implements Manager {
   ...
   private Recruiter recR;
   ...

   public void growTeam( Object criteria ){ 
      //...check preconditions
      Employee newB = recR.srcEmployee( criteria );
      //...whatever else
   }

   ...

} 

...

[test/myApp]
|_RecruiterStandIn «concrete»
|_ManagerImplTest   

...

public class RecruiterStandIn implements Recruiter { 

   Map<Object, Employee> reSrcPool = new HashMap<>();

   public RecruiterStandIn( ){ 
      // populate reSrcPool with dummy test data...
   }    

   public Employee srcEmployee( Object criteria ){
      return reSrcPool.get( criteria );
   }
}

...

public class ManagerImplTest {
   ...
   // Class Under Test
   private ManagerImpl mgr;

   // Collaborator
   private Recruiter recR = new RecruiterStandIn( );
   ...

   public void testGrowTeam(  ) {
      //...
      mgr.setRecruiter( recR ); 
      mgr.growTeam( criteria );
      // assertions follow...
   }

   ...    
}

...

Here are my questions: Given that I have a RecruiterStub concrete implementation that already exists within the codebase for testing purposes (in the test namespace), would it be redundant to also use a mock in the above unit test? What would be the value (if any) in additionally doing something like this in the above unit test?

...
@Mock
private Recruiter recR;
...

...
public void testGrowTeam(  ) { 
   ...
   expect( recR.srcEmployee( blah) ).andReturn( blah )...
   // exercising/assertions/validations as usual...
}
...

You can safely assume that RecruiterStub does everything the class under test will ever require of it for the purposes of the above unit test. That is to say, for the sake of simple answers/explanations, there's no need to overcomplicate the above scenario with contrived what-ifs around maintenance of the stub and whatnot.

Thanks in advance.

Automate Protractor / Selenium / Webdriver command

How should I aggregate starting my localhost server, running webdriver-manager start, and typing protractor conf.js.

I want to streamline this process.

Thoughts?

Write an alias? Edit my app.js file?

Django: Override Setting used in AppConfig Ready Function

We are trying to write an automated test for the behavior of the AppConfig.ready function, which we are using as an initialization hook to run code when the Django app has loaded. Our ready method implementation uses a Django setting that we need to override in our test, and naturally we're trying to use the override_settings decorator to achieve this.

There is a snag however - when the test runs, at the point the ready function is executed, the setting override hasn't kicked in (it is still using the original value from settings.py). Is there a way that we can still override the setting in a way where the override will apply when the ready function is called?

Some code to demonstrate this behavior:

settings.py

MY_SETTING = 'original value'

dummy_app/__init__.py

default_app_config = 'dummy_app.apps.DummyAppConfig'

dummy_app/apps.py

from django.apps import AppConfig
from django.conf import settings


class DummyAppConfig(AppConfig):
    name = 'dummy_app'

    def ready(self):
        print('settings.MY_SETTING in app config ready function: {0}'.format(settings.MY_SETTING))

dummy_app/tests.py

from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings


@override_settings(MY_SETTING='overridden value')
@override_settings(INSTALLED_APPS=('dummy_app',))
class AppConfigTests(TestCase):

    def test_to_see_where_overridden_settings_value_is_available(self):
        print('settings.MY_SETTING in test function: '.format(settings.MY_SETTING))
        self.fail('Trigger test output')

Output

======================================================================
FAIL: test_to_see_where_overridden_settings_value_is_available (dummy_app.tests.AppConfigTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/labminds/venv/labos/src/dom-base/dummy_app/tests.py", line 12, in test_to_see_where_overridden_settings_value_is_available
    self.fail('Trigger test output')
AssertionError: Trigger test output
-------------------- >> begin captured stdout << ---------------------
settings.MY_SETTING in app config ready function: original value
settings.MY_SETTING in test function: overridden value

--------------------- >> end captured stdout << ----------------------

It is important to note that we only want to override this setting for the tests that are asserting the behavior of ready, which is why we aren't considering changing the setting in settings.py, or using a separate version of this file used just for running our automated tests.

One option already considered - we could simply initialize the AppConfig class in our test, call ready and test the behavior that way (at which point the setting would be overridden by the decorator). However, we would prefer to run this as an integration test, and rely on the natural behavior of Django to call the function for us - this is key functionality for us and we want to make sure the test fails if Django's initialization behavior changes.

ng-class not evaluating during unit test

In attempting to unit test my custom directive, I ran into an issue trying to find an element with a dynamic class applied to it, based on an expression within an ng-class directive. It seems to me that the expression is just not evaluating at all. Is this possible to test? And if so, what am I doing wrong or missing?

The first unit test passes fine, the second is where the issue lies.

The tests:

beforeEach(inject(function ($rootScope, $compile) {

    scope = $rootScope.$new();

    element = '<tp-navigation-bar></tp-navigation-bar>';

    scope.currentPage = 'reports';
    scope.contactName = 'Test Name';
    scope.isLoggedIn = true;

    element = $compile(element)(scope);
    scope.$digest();
}));

it("should contain a dropdown with the contact name as the title", function () {

    expect(element.find('.dropdown-toggle span:nth-child(2)').text()).toEqual('Test Name');
});

it("should have reports set as the active page", function () {

    expect(element.find('li .active').text()).toEqual('Reports');
});

The template:

<ul class="nav navbar-nav navbar-right" ng-show="isLoggedIn">
    <li ng-class="{active:currentPage === 'mainDashboard'}">
       Home
    </li>
    <li ng-class="{active:currentPage === 'requests'}">
       Requests
    </li>
    <li ng-class="{active:currentPage === 'reports'}">
       Reports
    </li>
</ul>

How to write up a unit test in Jasmine for a random outcome? (eg Dice Throw)

How would one write up a Jasmine Unit Test, based around a random outcome generator?

For example, how does one write a test around the result of a random dice throw (or colour picker, or weather setting if it were a string)?

The dice code itself is along the lines of:

Dice.prototype.rollDice = function() {
1 + Math.floor(Math.random() * 6);
};

And I am aware that what is written below is incorrrect/ incomplete, I have simply written it as an example of where I am stuck:

it("can generate a random number from the players throw", function() {
var dice = new Dice();
dice.rollDice();
expect(----------------------).toEqual(----------------);
});

I have little experience with Jasmine Unit testing, and would appreciate a demonstration of a complete working example

Many thanks

Running Unit-Tests for a non-simulator / device architecture

I am appointed the task of making unit-tests for an SDK. Unfortunately I get the following error when trying to run a unit-test in the simulator:

ld: warning: ignoring file /Users/joeribultheel/Documents/Projects/Ios/plop-plopplop-ios/V3MockSDKTest/plop-plopplop-ios.framework/plop-plopplop-ios, missing required architecture x86_64 in file /Users/joeribultheel/Documents/Projects/Ios/plop-plopplop-ios/V3MockSDKTest/plop-plopplop-ios.framework/plop-plopplop-ios (3 slices) Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_Wrapper", referenced from:
  objc-class-ref in V3MockSDKTestTests.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried running the unit-tests on a physical device but no luck. Is this even possible? I tried with the default project-generated unit-test and it doesn't seem to work either.

In short: how can I unit-test code written for a device-architecture only ?

Thank you!

Simple Ember component test with computed properties

I know this should be simple, I'm just not doing something right, and haven't found the example to mimic nor I guess do I fully understand what should go inside an Ember.run()

Here is my component code:

import Ember from 'ember';
export default Ember.Component.extend({
  isGreen: function() {
    if (!status) { return ''; }
    return status.toUpperCase() === 'G';
  }.property('status')
});

My component template:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-green {{if isGreen 'active'}}">
    <input checked="checked" name="status" value="G" type="radio"/> Green
  </label>
  <label class="btn btn-yellow {{if isYellow 'active'}}">
      <input name="status" value="Y" type="radio"/> Yellow
  </label>
  <label class="btn btn-red {{if isRed 'active'}}">
      <input name="status" value="R" type="radio"/> Red
  </label>
</div>

And in my test:

test('status sets active class on the correct button', function(assert) {
  expect(3);
  var component = this.subject();

  //Green status
  Ember.run(function() {
    component.set('status', 'G');
  })
  equal(this.$().find('.btn-green.active').length, 1, 'When status is green, the green button has the active class');

I have three of these tests, one for each of three different statuses. If I have just one test, I don't need the to wrap component.set() in an Ember.run() in order for the test to pass. But if I have all three tests, I get this error:

You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run

But if I do put each of my component.set() calls in a run loop, then my tests fail due to the equal assertion expecting 1 and getting 0. I'm sure this is due to a lack of understanding on my part, but either the set() isn't running, or else the component gets re-rendered in the assertion and thus doesn't know that the status property was already set. I've been reading docs and googling for an hour, and haven't found a solution yet (and more beneficially, an explanation).

Jmockit getting null pointer exception on unit testing (testng) a getter method

I have the following code

//Unit to be tested (classname : PropertiesFile)
public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

where propertiesMap is a normal hashmap defined as Map propertiesMap;

Here is my TestNG test :

@Test()
public void testGetProperty1(@Mocked final Map<String, String> propertiesMap)

{
    new NonStrictExpectations()
    {{
            propertiesMap.get("region");
            result = anyString;
        }};

    PropertiesFile.getProperty("region");

}

I am getting NPE on return line.

Please let me know what I am doing wrong here? and how to get rid of this NPE and make the test work properly.

Python unittests cannot find email templates?

So I am working on some unit tests but I am running into a problem where when I testing to see if a new file is created or to see if an email is being sent the unit test either can't find the place to find the file or fails to create the file in the specified location. I know it works because when I run the code everything works flawlessly but when I try to run the code using the unittest module it fails the test. Any ideas why?

def generate_token(self, username):

    unique_id = str(uuid.uuid4()).replace("-", "").upper()

    file_path = os.path.abspath(os.path.join(os.getcwd(), 'tokens'))
    file_path = os.path.join(file_path, unique_id + '.txt')

    print file_path

    try:
        data = {
            "username": username,
            "date_created": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }
        file = open(file_path, "a")
        json.dump(data, file, indent=4)
        file.close()
        if(app.config['DEBUG']): print("File Created!")
    except:
        if(app.config['DEBUG']): print("Could not create new file!")

    return unique_id

In this method it cannot create the new token file for some reason

def __send_password_reset_email(self, first_name, username, email):
    is_prod = app.config['IS_PROD']
    root_url = app.config['DEV_URL']
    mail_host = app.config['DEV_MAIL_SERVER']
    if(is_prod):
        mail_host = app.config['PROD_MAIL_SERVER']
        root_url = app.config['PROD_URL']

    file = open('./emails/email-pwreset.htm', 'r')
    msg = file.read()
    file.close()

    msg = msg.replace('[FIRSTNAME]', first_name)
    msg = msg.replace('[USERNAME]', username)
    msg = msg.replace('[WEBSITEROOTURL]', root_url)

    mail_server = smtplib.SMTP(mail_host)
    msg = MIMEText(msg, 'html')
    from_addr = app.config['TAYLOR_EMAIL']

    msg['Subject'] = 'Your Taylor Password Has Been Reset'
    msg['From'] = from_addr
    msg['To'] = email

    if(not app.config['TESTING']):
        try:
            mail_server.sendmail(from_addr, email, msg.as_string())
        except smtplib.SMTPException, e:
            print(e)

    mail_server.quit()

It fails here when it tries to find the email folder.

I honestly have no idea what is wrong and I have no idea where to start to try and fix this.

How to mock getNamedParameterJdbcTemplate()

I am trying to mock a DAO implementation class that extends NamedParameterJdbcDaoSupport

This is how my DAO interface looks like:

public interface TestDAO{

List<String> search();

}

This is how my implementation class is:

    public class TestDAOImpl extends NamedParameterJdbcDaoSupport implements TestDAO {

    public List<String> search(){

    return getNamedParameterJdbcTemplate().query(mySQLQuery,myMapSqlParameterSource, myRowMapper);
    }
}

What I am trying to achieve is that write a mock test case to mock the behaviour of the call

getNamedParameterJdbcTemplate().query(mySQLQuery,myMapSqlParameterSource, myRowMapper)

So I want to implemented something like

when(getNamedParameterJdbcTemplate().query(mySQLQuery,myMapSqlParameterSource, myRowMapper)).thenReturn(whatIWantToReturn);

I am unable to find any information on this. Can someone guide me. How to do this?

public class TestDAOImplTestCase{

    @Test
    public void testSearch(){
        when(getNamedParameterJdbcTemplate().query(mySQLQuery,myMapSqlParameterSource, myRowMapper)).thenReturn(whatIWantToReturn); 
    } 
}

Ember Testing: Why use Assert.?

I see a lot of examples (including ember-cli generated tests) that use assert.function() but I can use the function as is, so am I doing something wrong, or do examples just show not-really-necessary qualifiers?

For example, either of these work in a new generated unit test:

assert.expect(1);

expect(1);

Why ever do the first one if the second one works?

Unit testing controller with injected dependencies

  1. What is the best practice to inject the dependencies into my controller test?
  2. When would I use the module(function($provide){})?
  3. How do I properly check that $state.go() was called with the right arguments?

example-controller.js

angular.module('myModule')
    .controller('ExampleCtrl', ['$state', 'ExampleService', 'exampleResolve',
      function($state, ExampleService, exampleResolve){
        var self = this;

        self.property = false;
        self.resolvedProperty = exampleResolve;

        self.submit = function() {
          ExampleService
            .exampleGet()
            .$promise
            .then(function(res) {
              $state.go('anotherView', { prop1: 'yay', prop2: 'again' });
            })
        };
      }]);

example-controller.test.js

   describe('Controller: ExampleCtrl', function() {
      beforeEach(module('myModule'));

      var ctrl,
          mockBackend,
          mockState;

      var mockExampleResolve = { test: 'Test' };

      // Provide any mocks needed
      // when do I provide mocks?
      beforeEach(function() {
        module(function($provide) {

        });
      });

      beforeEach(inject(function($controller, $httpBackend, exampleResolve, $state) {
        mockBackend = $httpBackend;
        mockState = $state;
        exampleResolve = mockExampleResolve;

        ctrl = $controller('ExampleCtrl');
      }));

      describe('initialization', function() {
        beforeEach(function() {});

        it('should exist', function() {
          expect(!!ctrl).toBe(true);
        });

        it('should initialize any view-model variables', function() {
          expect(ctrl.property).toBe('false');
          expect(ctrl.resolvedProperty).toEqual({test: 'Test'});
        });
      });

      describe('submit called', function() {
        beforeEach(function() {

        });

        it('should call state.go with the correct arguments', function() {
           // how do i check this?
        });

      });

    });

Dealing with HttpResponse in unit tests

I have a simple website that has one page. The function I am unit testing is

public void WriteFileToClient(string fileContent, string fileName)
        {
            StringWriter stringWriter = new StringWriter();
            stringWriter.Write(fileContent);
            Response.ContentType = "text/plain";
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.txt", fileName));
            Response.Clear();

            using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
            {
                writer.Write(stringWriter.ToString());
            }
            Response.End();
        }

When I run my test it says that Response is not available enter image description here

Here is my Unit test

[TestMethod]
        [TestCategory("Unit")]
        public void WriteFileToClient_ShouldSucceedForCorrectInput()
        {
            //Arrange
            Migrate migrate = new Migrate();
            Guid g = Guid.Parse("fffe49c1-a838-46bc-b5c6-4e0bbd3e4c32");

            string fileContent = migrate.GenerateFlatFileText(g);
            string fileName = string.Format("flat file - {0}.txt", g);

            //Ask
            migrate.WriteFileToClient(fileContent, fileName);

            //Assert
            migrate.Response.OutputStream.Should().NotBeNull();
            migrate.Response.ContentType.Should().Be("text/plain");
            migrate.Response.Headers.Should().HaveCount(1);
        }

Any suggestions on how to mock the response? honestly I don't understand why the Response object is not available, my Migrate class inherits Page and to my understanding should has the Response included

how can i angular unit test $http combine promise

Im very new in angularjs, so if my question disturb you, i so sorry ! Everything i write is run good, but now i want define a test file for settingcontroller using $httpBackEnd combine with promise ! but it not work ! can anyone help me !

In my case, i using:

var vormetricApp = angular.module('myApp','ngRoute','ngSanitize']);
vormetricApp.config([ '$routeProvider', function($routeProvider) {
    $routeProvider.when('/login', {
            templateUrl : '.....',
            controller  : '.......'
        }).when('/Setting', {
        templateUrl : 'settings.html',
        controller : 'settingController'
    }).when('/Backups', {
        templateUrl : 'app/views/settings/backup/backups.html',
        controller : 'backupController'
    }).when('/ffas', {
       ...................
    }).otherwise({
        redirectTo : '/'
    });
}])

in service i write:

myApp.factory('myservice', function($http, $q) {
    function myservice() {
        this.getSettings = function() {
            var deferred = $q.defer();
            $http({
                method : "GET",
                url : "test/views/settings/settingsdata.json",
            }).success(function(data) {
                deferred.resolve(data);
            }).error(function(msg, code) {
                deferred.reject(msg);
                $log.error(msg, code);
            });
            return deferred.promise;
        };
});

Here is setting controller

myApp.controller('settingController',function($scope, myservice) {

            var result = {};

            myservice.getSettings().then(
            function(pages) {
                $scope.pages = pages;
                result = pages;
            },
            /* error function */
            function(result) {
                console.log("Failed to get data, result is " + result);
            });

            var data = {};
            // Implement search function
            $scope.findValue = function(searchText) {
                angular.forEach(result, function(item) {
                    angular.forEach(item, function(index) {
                        if (index.name.toLowerCase().indexOf(
                                searchText.toLowerCase()) > -1) {
                            if (index.type == "Backup") {
                                if (!data.Backup)
                                    data.Backup = [];
                                data.Backup.push(index);
                            }
                            if (index.type == "System") {
                                if (!data.System)
                                    data.System = [];
                                data.System.push(index);
                            }
                            if (index.type == "Maintenance") {
                                if (!data.Maintenance)
                                    data.Maintenance = [];
                                data.Maintenance.push(index);
                            }
                            if (index.type == "Authentication") {
                                if (!data.Authentication)
                                    data.Authentication = [];
                                data.Authentication.push(index);
                            }
                            if (index.type == "Notification") {
                                if (!data.Notification)
                                    data.Notification = [];
                                data.Notification.push(index);
                            }
                        }
                    });
                });
                $scope.pages = data;
                data = {};
            };
});

My setting data

{  
   "System":[  
      {  
         "link":"#/",
         "name":"Display",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Email",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Log Preference",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Miscellaneous",
         "content":".............",
         "description":"...............",
         "type":"......"
      }
   ],

   "Backup":[  
      {  
         "link":"#/",
         "name":"About",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Wrapper Keys",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Backups",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#/",
         "name":"Restore",
         "content":".............",
         "description":"...............",
         "type":"......"
      }
   ],

   "Maintenance":[  
      {  
         "link":"#",
         "name":"Upload License",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"Upgrade",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"Software Version",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"Network Diagnostics",
         "content":".............",
         "description":"...............",
         "type":"......"
      }
   ],

   "Authentication":[  
      {  
         "link":"#",
         "name":"WebCertificate",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"RSA",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"LDAP",
         "content":".............",
         "description":"...............",
         "type":"......"
      }
   ],

   "Notification":[  
      {  
         "link":"#",
         "name":"SNMP",
         "content":".............",
         "description":"...............",
         "type":"......"
      },
      {  
         "link":"#",
         "name":"Email",
         "content":".............",
         "description":"...............",
         "type":"......"
      }
   ]   
}

my setting controller test

describe('settingController test', function() {
    var dataSetting = {
        "System" : [ {
            "link" : "#/",
            "name" : "Display",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Email",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Log Preference",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Miscellaneous",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        } ],

        "Backup" : [ {
            "link" : "#/",
            "name" : "About",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Wrapper Keys",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Backups",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#/",
            "name" : "Restore",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        } ],

        "Maintenance" : [ {
            "link" : "#",
            "name" : "Upload License",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "Upgrade",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "Software Version",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "Network Diagnostics",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        } ],

        "Authentication" : [ {
            "link" : "#",
            "name" : "WebCertificate",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "RSA",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "LDAP",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        } ],

        "Notification" : [ {
            "link" : "#",
            "name" : "SNMP",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        }, {
            "link" : "#",
            "name" : "Email",
            "content" : ".............",
            "description" : "...............",
            "type" : "......"
        } ]
    };
    var $httpBackend, $rootScope, createController, settingHandler;
    beforeEach(angular.mock.module("myApp"));
    beforeEach(angular.mock.inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        settingHandler = $httpBackend.when('GET',
                'test/views/settings/settingsdata.json').respond(dataSetting);
        $rootScope = $injector.get('$rootScope');
        var $controller = $injector.get('$controller');
        createController = function() {
            return $controller('settingController', {
                '$scope' : $rootScope
            });
        };
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should fetch get data setting', function() {
        $httpBackend.expectGET('test/views/settings/settingsdata.json');
        var controller = createController();
        $httpBackend.flush();
    });

    it('test function findvalue', inject(function($q, $rootScope) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var resolvedValue;
        var data = dataSetting;

        promise.then(function(data) {
            resolvedValue = data;
        });
        deferred.resolve(dataSetting);
        var expectSystemData = [ {
            "link" : "#/Display",
            "name" : "Display",
            "content" : "Display this option here",
            "description" : "This is description of the System Settings",
            "type" : "System"
        } ];
        $rootScope.$apply();
        var controller = createController();
        $rootScope.findValue('Display');
        expect($rootScope.pages.System).toEqual(expectSystemData);
    }));
});

I want test function findValue(searchText), but when i run test , i found a testcase is fail The result is:

        Expected undefined to equal [ Object({ link: '#/Display', name: 'Display', content: '.............', description: '...............', type: '......' }) ].
            at Object.<anonymous> (E:/TEST/webapp/test/views/settings/settingcontroller.test1.js:161:35)
            at Object.invoke (E:/TEST/webapp/app/lib/angular/angular.js:4443:17)
            at Object.workFn (E:/TEST/webapp/test/lib/angular/angular-mocks.js:2420:20)
        Error: Unflushed requests: 1
            at Function.$httpBackend.verifyNoOutstandingRequest (E:/TEST/webapp/test/lib/angular/angular-mocks.js:1564:13)
            at Object.<anonymous> (E:/TEST/webapp/test/views/settings/settingcontroller.test1.js:132:16)
Chrome 43.0.2357 (Windows 10 0.0.0): Executed 2 of 2 (1 FAILED) (0.037 secs / 0.03 secs)

Please help me for define a test settingController with using both htppBackend and Promise !!

thanks so much !

How to test Web.API method with RestSharp passing in ClaimsPrincipal

I'm having a bit of trouble with a specific implementation of testing out my Web.API methods using RestSharp. I have been very successful in performing POSTS and GETS in my open (non-secured) methods. However, when I have to send in a token to determine access I have problems.

Here is the implementation:

I am using OWIN middleware for my Web.API. The client must post to a token service in order to get the given Token that contains their claims. All of this has been working fine.

In my test my Initializer has the following code that posts to the token service and gets back the token. This works wonderfully - returns back the token as advertised:

 [TestInitialize]
    public void SetupTest()
    {

        _verificationErrors = new StringBuilder();

        _client = new RestClient
        {
            BaseUrl = new Uri(ConfigurationManager.AppSettings["ServicesBaseUrl"])
        };

        _serviceRequestPrepender = ConfigurationManager.AppSettings["ServiceRequestPrepender"];

        // Initialize this by getting the user token put back for all of the tests to use.
        var request = new RestRequest(string.Format("{0}{1}", _serviceRequestPrepender, ConfigurationManager.AppSettings["TokenEndpointPath"]), Method.POST);

        // Add header stuff
        request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
        request.AddParameter("Accept", "application/json", ParameterType.HttpHeader);

        // Add request body
        _userName = "{test student name}";
        _password = "{test student password}";
        _userGuid = "{this is a guid value!!}";

        _clientIdentifier = ConfigurationManager.AppSettings["ClientIdentifier"];
        _applicationId = ConfigurationManager.AppSettings["ApplicationId"];

        string encodedBody = string.Format("grant_type=password&username={0}&password={1}&scope={2} {3} {4} {0}"
                                           , _userName, _password, _clientIdentifier, _userGuid, _applicationId);
        request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);


        // execute the request
        IRestResponse response = _client.Execute(request);

        // Make sure everything is working as promised.
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        Assert.IsTrue(response.ContentLength > 0);

        _token = new JavaScriptSerializer().Deserialize<Token>(response.Content).access_token;

    }

Next is the following code that calls a Web.API method which passes the given token along to another Web.API method where I'm performing a GET to extract some information from my service.

        [TestMethod]
    public void GetUserProfileTest()
    {

        // Arrange
        var request = new RestRequest(string.Format("{0}{1}", _serviceRequestPrepender, "api/UserProfiles/UserProfiles/Get/{appId}/{userId}/{username}"), Method.GET);

        // Add header stuff
        request.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
        request.AddParameter("Accept", "/application/json", ParameterType.HttpHeader);
        request.AddParameter("Authorization", string.Format("{0} {1}", "Bearer", _token));

        request.AddUrlSegment("appId", "1");
        request.AddUrlSegment("userId", _userGuid);
        request.AddUrlSegment("username", _userName);

        // execute the request
        IRestResponse response = _client.Execute(request);

        // Make sure everything is working as promised.
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        Assert.IsTrue(response.ContentLength > 0); // do more when working

    }

Next, the service is called, but I have decorated the Web.API method with a custom access security check. This is a VERY simple security check in that it only checks to see if the token is valid and not expired. Here is the IsAuthorized method of that attribute:

        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // Custom Code here
        return ValidityChecker.IsTokenValid(actionContext);
    }

The ValidityChecker is a simple class that only checks to see if the token is valid:

    public class TokenValidityChecker
{
    public ClaimsPrincipal PrincipalWithClaims { get; private set; }

    /// <summary>
    /// Extracts out the ability to perform token checking since all Token checking attributes will need t his.
    /// </summary>
    /// <param name="actionContext"></param>
    /// <returns></returns>
    public bool IsTokenValid(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        bool result = false;

        var principal = actionContext.RequestContext.Principal;
        if (principal.GetType() == typeof(ClaimsPrincipal))
        {
            PrincipalWithClaims = (ClaimsPrincipal)principal;
            result = PrincipalWithClaims.Identity.IsAuthenticated;
        }

        // Custom Code here
        return result;
    }
}

So, with the background in place - here is the question. As you can see, normally, when the service is called the ValidityChecker will receive an HttpActionContext. Along with that, the RequestContext.Principal of that HttpActionContext will normally be of type ClaimsPrincipal.

However, when running from a unit test and using RestSharp it is, of course, a WindowsPrincipal.

Is there a way using RestSharp to make that a ClaimsPrincipal? I've tried to ensure the token is included in the header using the Authorization parameter, but have not had any luck.

How to use mockery to mock global class without namespace?

I would like to test my WordPress application which calls this function http://ift.tt/1JuHcSx

I'm not sure how to mock that because WPCom_Related_Posts is not namespaced.

This is how I use the class

$related_posts = WPCom_Related_Posts()->get_related_posts( get_queried_object_id(), $args );    

How should I mock this get_related_posts in the test because this class will call Elasticsearch to get related posts and I don't want to set that up in PHPUnit

Unit testing an SQL query Python using Mock

I have a class called Loader, which loads datasets from an SQL server via queries. Such that by invoking loadFromSQL(query) in Loader, one gets the table as specified by query. The specific structure of Loader is:

import petl as etl
import pandas as pd

class Loader:
    """
    This is a class from which one can load data from an SQL server.
    """

    def __init__(self, connection_string):
        """
        This is the initialization file, and it requires the connection_string.

        :param connection_string:
        :type connection_string: str
        :return:
        """

        self.connection = pyodbc.connect(connection_string)

    def loadFromSQL(self, query):
        """
        This function loads the data according to the query passed in query.

        :param query:
        :type query: str
        """

        self.originalTableETL = etl.fromdb(self.connection, query)

        self.originalTablePD = etl.todataframe(self.originalTableETL)

Now, the thing is that I wish to test this class, i.e. to verify that the SQL querying is correct. From scouring the web I found that Mock could do the trick - the problem is that I'm not really sure how to do this when I have a database. In fact, I do not even know where to start as I haven't found any examples relating to my problem. Do you guys have any tips and/or a good documentation relating to my problem? Thanks!

Jasmine: Mocking multiple Jquery Selectors that call same function

In JavaScript, I have a function I'd like to test using Jasmine 2.1.3:

   function someFunction(){
     var $firstSelector = $("#firstSelector").val();
     var $secondSelector = $("#secondSelector").val();

     // some function logic
}

How can I spy on the $firstSelector.val() and $secondSelector.val() to provide defined return values for each to test my function? e.g (i want to spy on $firstSelector.val() to return "Hello" and $secondSelector.val() to return "World").

I have read answers that allude to spying on the generic $.fn and returning a value for val. But I am unsure how it will give me the control of manually setting return values for different JQuery selector passed in. Is there a concept here I am missing?

Is it possible to have this level of control in terms of mocking JQuery $(someSelectorVariable).val() with different selectors as parameters?

Unit Testing with ASP.NET webservice?

I am trying to unit test some of the methods I have written in an ASP.NET web service. To the project I have added a new Unit Test Project but the problem is I can't access the classes and methods from the unit test class. How can I fix this issue ?

pypy interpreter does not recognize nosetests while pypy3 does

I have written a script to test my Python library over different versions of python. For pypy3,

python setup.py test

Works just fine. But on pypy, It runs 0 tests. No failure, but zero tests. Here is my script

language: python

matrix:
  include:
    - python: "pypy"
      env:
        - TEST_PY3="false"
    - python: "pypy3"
      env:
        - TEST_PY3="true"


before_install:

 - sudo apt-get update
 - sudo apt-get install build-essential

install:
  - if [[ "${TEST_PY3}" == "false" ]]; then
      pip install Cython;
      python setup.py install;
    fi

  - if [[ "${TEST_PY3}" == "true" ]]; then
      pip install Cython;
      python setup.py install;
    fi

script:
 - python setup.py test

I am using nosetests. This part of my setup.py might be helpful

test_suite         = 'nose.collector',
tests_require      = ['nose>=0.10.1']

Is there any problem of nosetests with pypy?

Karma testing adding unnecessary folders to path

I'm trying to do some unit testing and I'm at the end of my rope. I've moved files, rewritten things countless times, and I still can't get the damn thing to work. I've followed this tutorial exactly and it still doesn't work.

When I run "gulp tests", and I am in my ~/git/mobile directory, I get the following output

Josh@DAEDALUS ~/git/mobile (unit-testing)
$ gulp test 
[10:28:40] Using gulpfile c:\Users\Josh\git\mobile\gulpfile.js
[10:28:40] Starting 'test'...
WARN [watcher]: Pattern  "c:/Users/Josh/git/mobile/tests/www/lib/angular/angular.
js" does not match any file.
WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/node_modules/angular-moc
ks/angular-mocks.js" does not match any file.
WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/www/js/app.js" does not
 match any file.
WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/www/js/controller.js" do
es not match any file.
WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/www/js/services.js" does
not match any file.
 WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/tests/Controllers/contro
 llers.tests.js" does not match any file.
WARN [watcher]: Pattern "c:/Users/Josh/git/mobile/tests/tests/Services/services.
tests.js" does not match any file.
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Windows 8 0.0.0)]: Connected on socket --QoOiVt0ZraOpiQ3q
zd with id 22369565
PhantomJS 1.9.8 (Windows 8 0.0.0): Executed 0 of 0 ERROR (0.003 secs / 0 secs)
[10:28:42] Finished 'test' after 2.19 s

See, I don't get why it decides that it wants to add the /tests/ folder out of nowhere. It's not in my directory. For example, a proper path would be c:/users/josh/git/mobile/www/js/controller.js That tests folder isn't there. There is a tests folder in my mobile directory, but it doesn't contain anything but my "my.conf.js" and two subdirectories which contain my test files. I cannot for the life of me figure out what's wrong. I've tried adding ../, ./, /, or removing that all together from the beginning of my files paths in my.conf.js. Here is the contents of "my.conf.js" Here is the contents of "gulpfile.js"

Handling a post in angular unit tests

In my Angular app I have a view that, as soon as it is loaded a POST is made. At first I was getting this Error:

"Unexpected request: POST /api/stuff

Now however I have inserted this code:

$httpBackend.expectPOST("/api/stuff",[{}]).respond(200,{});

This removes the initial error but instead I am left with this Error:

"message": "Expected POST /api/stuff with different data
EXPECTED: [{}]
GOT:      {}"

If anyone has any ideas on how to resolve this, that would be greatly appreciated. If more code is needed please ask. Thanks in advance.

Dependancy Injection in a static class

I am writing Unit Tests for an existing code base, and am still getting up to speed.

There is a static Logger class which is written like this (simplified):

public static class Logger
{
    public static void Log(string message)
    {
        var myService = new Service();
        myService.Save(message);
    }
}

I would like to be able to Mock (using Moq) the Service class so I can verify the result. But there is obviously no way to do that with the class as it exists. But I don't see how the Service dependency can be injected into the static class so that it can be mocked. Is there a way to do that? Or should it not have been written as a static class?

Test if method in ClassA has been called from another method in ClassA

It is possible to test if a method has been called using Moq and dependency injection. However, is it possible to test if one method in a class calls another within the same class?

In example, I want to test that if I log a certain exception, that an information message is logged as well.

The method is:

public void Error(string message, Exception exception, long logId = 0)
{
    var int32 = (int)logId;
    Info("Id was converted to an int so that it would fit in the log: " + logId, int32);
    Error(message, exception, int32);
}

This was my attempt at unit testing it. It fails... can it be done?

void logging_an_error_with_a_long_id_also_logs_info()
{
    var mock = new Mock<ILogger>();
    var testedClass = new Logger();
    var counter = 0;

    testedClass.Error("test" + counter++, new Exception("test" + counter), Int64.MaxValue);

    mock.Verify(m => m.Info(It.IsAny<string>(), It.IsAny<int>()));
}

Since the info and error methods are in the same class (ClassA), I don't believe I can pass ClassA as a dependency into ClassA. So don't test it?

Mock image for tests in Django

I want to use mock-image for creating an object in Django.

tests.py:

from django.test import TestCase
from .models import MyModel
from unittest import mock
from django.core.files import File


class MyModelTestCase(TestCase):

    def setUp(self):
        file_mock = mock.Mock(spec=File, name='FileMock')
        file_mock.name = 'test.png'
        MyModel.objects.create(img=file_mock, name='123',)

    def test_creation(self):
        obj =  MyModel.objects.get(name='123')
        self.assertEqual(obj, '1, 123')

But I have an error:

TypeError: 'Mock' does not support the buffer interface

I use spec-argument, how it described in documentation.

Why it does not work and how to fix that?

Thanks!

Mockito's .when call seems to increase call count.

Using the following code:

@Test
public void testSetGameType_deathmatch() {
    CommandSender sender = Mockito.mock(CommandSender.class);
    String[] args = {"deathmatch"};
    Pvpgames plugin = PowerMockito.mock(Pvpgames.class, Mockito.withSettings().verboseLogging());
    plugin.settings = new HashMap<>();
    Server server = PowerMockito.mock(Server.class);
    PluginManager pluginManager = PowerMockito.mock(PluginManager.class);
    PowerMockito.when(plugin.getServer()).thenReturn(server);
    PowerMockito.when(plugin.getServer().getPluginManager()).thenReturn(pluginManager);
    PowerMockito.when(plugin.getServer().broadcastMessage(org.mockito.Matchers.anyString())).thenReturn(1);
    PowerMockito.when(plugin.getGameType()).thenCallRealMethod();
    Mockito.when(plugin.setActiveListener(Mockito.any())).thenCallRealMethod();

    boolean result = GametypeHandler.setGameType(sender, args, plugin);

    Assert.assertTrue(result);
    Mockito.verify(plugin).setActiveListener(Mockito.any(DeathMatchListener.class));
    Mockito.verify(plugin.getServer().getPluginManager()).registerEvents(Mockito.any(DeathMatchListener.class), Mockito.same(plugin));
    Mockito.verify(sender).sendMessage(Mockito.anyString());
    Mockito.verify(plugin.getServer()).broadcastMessage("Gametype has been changed to: Deathmatch");
}

When I verify Mockito.verify(plugin).setActiveListener(Mockito.any(DeathMatchListener.class)); .setActiveListener has apparently been called 3 times, however tracing it with my IDE tells me it has only been called once. So I enabled verbose logging in mockito and I get this as output:

############ Logging method invocation #1 on mock/spy ########
pvpgames.getGameType();
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:57)
   has returned: "null"

############ Logging method invocation #2 on mock/spy ########
pvpgames.setActiveListener(null);
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:58)
   has returned: "null"

############ Logging method invocation #3 on mock/spy ########
   stubbed: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:58)
pvpgames.setActiveListener(
    dk.zlepper.pvpgames.listeners.DeathMatchListener@3ddc6915
);
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandler.setGameType(GametypeHandler.java:22)
   has returned: "dk.zlepper.pvpgames.listeners.DeathMatchListener@3ddc6915" (dk.zlepper.pvpgames.listeners.DeathMatchListener)

############ Logging method invocation #4 on mock/spy ########
   stubbed: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:58)
pvpgames.setActiveListener(
    dk.zlepper.pvpgames.listeners.DeathMatchListener@3ddc6915
);
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandler.setGameType(GametypeHandler.java:22)
   has returned: "dk.zlepper.pvpgames.listeners.DeathMatchListener@3ddc6915" (dk.zlepper.pvpgames.listeners.DeathMatchListener)

############ Logging method invocation #5 on mock/spy ########
   stubbed: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:57)
pvpgames.getGameType();
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandler.setGameType(GametypeHandler.java:37)
   has returned: "Deathmatch" (dk.zlepper.pvpgames.commands.GameType)

############ Logging method invocation #6 on mock/spy ########
   stubbed: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:57)
pvpgames.getGameType();
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandler.setGameType(GametypeHandler.java:37)
   has returned: "Deathmatch" (dk.zlepper.pvpgames.commands.GameType)

############ Logging method invocation #7 on mock/spy ########
pvpgames.setActiveListener(null);
   invoked: -> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:63)
   has thrown: class org.mockito.exceptions.verification.TooManyActualInvocations with message 
pvpgames.setActiveListener(null);
Wanted 1 time:
-> at dk.zlepper.pvpgames.commands.GametypeHandlerTest.testSetGameType_deathmatch(GametypeHandlerTest.java:63)
But was 3 times. Undesired invocation:
-> at dk.zlepper.pvpgames.commands.GametypeHandler.setGameType(GametypeHandler.java:22)

So it seems like mockito counts it's own .when call as a call in the verify method. Have I done something wrong, or is this a bug in mockito?

Grails Unit testing GORM global constraints

I have an issue where the global constraints setup in the Config are not working when running unit tests.

This is in my Config.groovy: grails.gorm.default.constraints={ '*'(nullable:true, bindable:true) }

in my test I have tried this: static doWithConfig(c){ c.grails.gorm.default.constraints={ '*'(nullable:true, bindable:true) }

and also in the setupSpec(): grailsApplication.config.grails.gorm.default.constraints={ '*'(nullable:true, bindable:true) }

All I'm doing in my test is trying to create a domain object from a json string. Is there anything special that I should be doing to get this to work in the Unit test?

AngularJs testing. Where to put template

I am currently testing an angularjs directive. This directive has a templateUrl. I would lke to test the view to make sure it was initialized correctly i.e. correct number of buttons, certain elements hidden.

The problem I am having is that when I insert my html file into the template cache I still get :

"message": "Unexpected request: GET partials/stuff/stuff-leader.html

I assumed that when I used the templateCache I would no longer have to use:

 $httpBackend.whenGET("partials/stuff/stuff-leader.html").respond([{
        userId: 000
    }]);

but this does not seem to be the case. I am wondering am I correctly inserting the template, here is how I am doing it:

 template = $templateCache.get('/full/root/disk/path/to/file/stuff/stuff-leader.html');
    $templateCache.put('/myApp/templates/stuff-leader.html',template);

Is this correct, or should I be placing it somewhere else?

Unit Testing: Test if internal function is called or not ? Using Sinon and Chai

Consider log.js has function:

var function processData()
{
     if(condition)
          dbInsert();
}

var function dbInsert()
{
  // do some insertion
}

Now I want to test that when processData is called whether dbInsert is called or not. This is my test.js. Which fails test on the last one although when I manually check the db there does exist an entry

it('n number of times called', function() {

    var Data = '{"name":"abc"}';

    var spy = sinon.spy(log, "processData");
    var spy2 = sinon.spy(log, "dbInsertion");



    log.processServerLog(Data);                 

    expect(spy.callCount).to.be.equal(1);
    expect(spy2.called).to.be.true;   // returns false .. 

});

spec is undefined in file:///E:/jasmine-standalone-2.3.4/lib/angularjs/angular-mocks.js

I am new to Jasmine and have started testing my angular applications.I am persistently getting the error spec is undefined in file:///E:/jasmine-standalone-2.3.4/lib/angularjs/angular-mocks.js

and have been unable to identify the problem.

here are the parts of my SpecRunner.html file

<script src="lib/jasmine-2.3.4/jasmine.js"></script>
<script src="lib/jasmine-2.3.4/jasmine-html.js"></script>
<script src="lib/jasmine-2.3.4/boot.js"></script>

<script src="lib/angularjs/angular.min.js"></script>
<script src="lib/angularjs/angular-mocks.js"></script>



<!-- include source files here... -->
<script src="src/scribePanelController.js"></script>


<!-- include spec files here... -->
<script src="spec/scribePanelControllerSpec.js"></script>

and here is the code from spec file

'use strict';

 describe("scribePanelController", function() {

var $rootScope, $scope,$compile;
var $controller, service;

// Load the module
beforeEach(module('scribeModule'));

    beforeEach(inject(function(_$compile_,_$rootScope_,_$controller_,_scribePanelSharedService_){
// The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    $controller = _$controller_;
    service = _scribePanelSharedService_;

    $controller('scribePanelController', { '$scope': $scope,'myScribePanelSharedService': service});
    $rootScope.$apply(); // promises are resolved/dispatched only on next $digest cycle
}));

it('should check whether controller exists', function() {
    expect($controller).not.toBeNull();
});

it('it should make isMoreAsmtPresent false', function() {
    expect($scope.service.isMoreAsmtPresent == 'active');
  });

});

Unit testing with `OCMock`

I want to cover MYImageLoader class with unit tests using OCMock. On of the tests makes sure that when it downloads an image it copies the file from the location returned in a NSURLSessionDownloadTask callback to a temporary location. And here I am trying to write a good unit test I do not want to test method implementation details. So I pass a mock of a NSFileManager class in the constructor of MYImageLoader class. But there are several equally possible to use NSFileManager methods to copy a file:

- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error;
- (BOOL)moveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error;
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;

So what would be the good practice here? I don’t want my unit tests to determine which methods I should use in the method implementation just to make sure the test passes.

Is there anything like expect this or this or this in OCMock?

Or may be you can advise a different approach?

Set SQLite as database for unit testing in Laravel 5.1

I'm trying to set-up unit testing in Laravel 5.1. Following the documentation I see this:

Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box

and

When running tests, Laravel will automatically set the configuration environment to testing. Laravel automatically configures the session and cache to the array driver while testing, meaning no session or cache data will be persisted while testing.

which is awesome. But... how do I tell Laravel to use SQLite database connection when tests are ran?

Only thing there is in config/database.php is this commented code:

/* We might use this connection for unit tests
'sqlite' => [
    'driver'   => 'sqlite',
    'database' => storage_path().'/database.sqlite',
    'prefix'   => '',
],
*/

We might use this :)

Is there a way to set this globally for all test? Do I need to set the connecton in every test case?

Any help appreciated.

lundi 29 juin 2015

Unit testing with $httpbackend mocks and typescript

I'm trying to unit test a method that makes an http request with the $http service, however the $httpbackend mock does not seem to be intercepting the request - I get a Error: No pending request to flush ! error.

My test is as follows:

/// <reference path="../typings/tsd.d.ts" />
/// <reference path="../dist/ngJwtAuth.d.ts" />


var expect = chai.expect;

describe('Service tests', () => {

    var $httpBackend:ng.IHttpBackendService;
    var ngJwtAuthService:NgJwtAuth.NgJwtAuthService;

    beforeEach(()=>{

        module('ngJwtAuth');

        inject((_$httpBackend_, _ngJwtAuthService_) => {
            $httpBackend = _$httpBackend_;

            if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton
                ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider
            }
        })
    });

    afterEach(() => {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be an injectable service', () => {

        return expect(ngJwtAuthService).to.be.an('object');
    });

    it('should retrieve a json web token', () => {

        var user = {
            email: 'joe.bloggs@example.com',
            password: 'password'
        };

        $httpBackend.expectGET('/api/auth/login', (headers) => {
            return headers['Authorization'] == 'Basic '+btoa(user.email+':'+user.password);
        });

        var promisedToken = ngJwtAuthService.authenticate(user.email, user.password);

        promisedToken.then((res) => {

            console.log('res', res);
        });

        $httpBackend.flush();

    });


});

The results I get is

Start:
  Service tests
    ✔ should be an injectable service
    ✖ should retrieve a json web token
    ✖ "after each" hook

Finished in 0.055 secs / 0.004 secs

SUMMARY:
✔ 1 tests completed
✖ 2 tests failed

FAILED TESTS:
  Service tests
    ✖ should retrieve a json web token
      Chrome 43.0.2357 (Mac OS X 10.10.3)
    Error: No pending request to flush !
        at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:104:22)

    ✖ "after each" hook
      Chrome 43.0.2357 (Mac OS X 10.10.3)
    Error: Unsatisfied requests: GET /api/auth/login
        at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:86:22)

The offending method that I am testing is

public authenticate(username:string, password:string): ng.IPromise<Object>{

    var authHeader = NgJwtAuthService.getAuthHeader(username, password);

    var requestConfig:ng.IRequestConfig = {
        method: 'GET',
        url:  this.getLoginEndpoint(),
        headers: {
            Authorization : authHeader
        },
        responseType: 'json'
    };

    return this.$http(requestConfig);
}

The whole project can be found at http://ift.tt/1ROG8I9

Mockito - mock static methods for helper class called from main class

I have a main class from which I am writing the unit test. The main class calls the helper class methods which consume a lot of CPU cycle. I want to mock helper class methods so that whenever I call main class methods - it calls the mock helper methods instead of the real ones.

I want the code inside the main class method to execute - just that when it comes to calling the method from helper class - it calls the mock method.

Here's the structure.

MainClass.py

import helperClass as  helper
Class MainClass:
    def testMethod(self):
        helper.methodWhichIwantToMock()

helperClass.py just has one method

def methodWhichIwantToMock():
    print "I love CPU cycles"

I read that I could spy on the MainClass in a way that when certain dependent methods are called within MainClass - I can mock them and return what I want. But in this case the methods I want to mock are in different class from the one I am testing.

Python unit test mock, get mocked function's input arguments

I want a unit test to assert that a variable action within a function is getting set to its expected value, the only time this variable is used is when it is passed in a call to a library.

Class Monolith(object):
    def foo(self, raw_event):
        action =  # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

My thought was that I could mock lib.event.Event, and get its input arguments and assert they are of specific value.

>Is this not how mocks work? The mock documentation frustrates me with its inconsistency, half-examples, and plethora of examples that are not related to what I want to do.

Unit testing $http resolve in controller

I need help with my controller test. I have a resolve using ui-router. In my test, I need to figure out how to handle the resolve's exampleData.

config.js

angular.module('myModule')
  .config(['$stateProvider', '$urlRouterProvider',

    function($stateProvider, $urlRouterProvider) {

      $stateProvider
        .state('site', {
          abstract: true,
          resolve: {
            exampleData: function(ExampleService) {
              // ExampleService.get() makes an $http call
              return ExampleService.get();
            }
          },
          // etc
        })
        .state('example', {
          parent: 'site',
          url:'/example',
          controller: 'ExampleCtrl as example',
          templateProvider: function($templateCache) {
            return $templateCache.get('views/example.html');
          }
        });

    }]);

example-controller.js

angular.module('myModule')
  .controller('ExampleCtrl', ['exampleData',
     function(exampleData) {

       var self = this;
       self.exampleData = exampleData;

       // self.exampleData should output something like
       // [
       //   {id: 1, title:'something'},
       //   {id: 2, title:'something'},
       //   {id: 3, title:'something'}
       // ]

  }]);

example-controller.test.js

   describe('Controller: ExampleCtrl', function() {
      beforeEach(module('myModule'));

      var ctrl;

      beforeEach(inject(function($controller) {
        ctrl = $controller('ExampleCtrl');
      }));

      describe('initialization', function() {
        beforeEach(function() {});

        it('should exist', function() {
          expect(!!ctrl).toBe(true);
        });

        it('should ...', function() {
          // do something
        });
      });

When I run the tests, I get the following error:

Unknown provider: exampleDataProvider <- exampleData <- ExampleCtrl

My question is: what do I do in order to test the resolve in my ExampleCtrl? The ExampleService.get() is a service which makes an $http call and returns and array of objects.

Unable to load AngularJS dependencies in Jasmine + Karma

Sorry that this question might seem newbie but I have just started learning on unit testing on my own and I have been struggling to get unit testing set up in Jasmine/Karma + AngularJS (Following John Papa's style). It has been bugging me for a couple days now.

(function() {
    var myModule = angular.module("myApp").controller("myCtrl", myCtrl);

    myCtrl.$inject = [];

    function myCtrl() {
        var vm = this;
        vm.sum = sum;

        function sum(x, y) {
            return x + y;
        }
    }
})();

controller.js

describe("Calculate sum", function(){
    beforeEach(module('myApp'));

    var controller;
    beforeEach(inject(function($controller) {
        controller = $controller('myCtrl', {}); 
    }));

    it("myCtrl is defined", function(){
        expect(controller).toBeDefined(); //
    })
});

controller.spec.js

Result of the test:

FAIL. Expect undefined to be defined

My file structure:

Karma Configuration below:

// Karma configuration
// Generated on Mon Jun 22 2015 18:06:04 GMT+0800 (Malay Peninsula Standard Time)

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',


        // frameworks to use
        // available frameworks: http://ift.tt/1ft83uu
        frameworks: ['jasmine'],


        // list of files / patterns to load in the browser
        files: [
            'js/angular.min.js',
            'js/angular-mocks.js',
            'modules/myCtrl/controller.js',
            'tests/**/*.test.js'
        ],


        // list of files to exclude
        exclude: [
            // 'js/angular-animate.min.js',
            // 'js/angular-sanitize.min.js',
            // 'js/angular-ui-router.js',
            // 'js/angular.js'
        ],


        // preprocess matching files before serving them to the browser
        // available preprocessors: http://ift.tt/1gyw6MG
        preprocessors: {},


        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: http://ift.tt/1ft83KQ
        reporters: ['progress'],


        // web server port
        port: 9876,


        // enable / disable colors in the output (reporters and logs)
        colors: true,


        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        // logLevel: config.LOG_INFO,
        logLevel: config.LOG_DISABLE,


        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,


        // start these browsers
        // available browser launchers: http://ift.tt/1ft83KU
        browsers: ['PhantomJS'],


        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    });
};

Would really appreciate any help/guidance on the direction to identify the error. *The code in the controller is working in the app. I took a working code and tried to do unit testing on it.

Creating system test environment

I have system that consists of device that is connected to PC and controlled with cross platform (Linux and Windows) function library. Under Windows this library is created with visual c++, under Linux - gcc. I need to create testing system that could test library code that is written in C++ and whole system behavior. With help of special functions I can get state of device that could be compared to expected one after calling some functions in library. I have no experience in unit testing at all. Would you point me on way I should go to make this system test environment.

Is there a way to make a setUp and tearDown methods on tape?

I am using tape for testing in JavaScript, but in some cases I want to set some configuration variables that are available in all the tests within a file. Something like the setUp and tearDown methods available in PhpUnit. Those methods will be executed before and after every test in the file, respectively.

e.g:

test("setUp", function(t){
    var person = {name: 'Jose', programmer: true};
});

test("Name isn't undefined", function(){
    t.notEqual(person.name, undefined);
});

test("Is a programmer", function(t){
    t.ok(person.programmer);
});

test("tearDown", function(){
    //Do something else
});

Dependency injection for unit testing vs. class managing its own variables

I have a class that is something like this (very simplified but this is the general idea. I'm not actually using the raw socket type):

class ConnectionBroker {

    private Socket socket;

    public ConnectionBroker(ConnectionDetails details) {
        socket = new Socket(details)
        //set socket paramaters
    }

    public sendOverConnection(String message) {
        //processing of message and internal queuing based on priority
        socket.send(message);
    }

    public shutdown() {
        socket.close();
    }
}

It would be valuable if I could unit test the class's functions by mocking the socket variable to check what is being sent over the socket. The standard way of doing this that I have seen is modifying the constructor to be

public ConnectionBroker(Socket socket) {
    this.socket = socket;
}

This would make unit testing a lot easier, however I have a number of issues with doing it this way:

  • The socket should be maanged only by the ConnectionBroker class
  • The fact that the ConnectionBroker class uses sockets at all should be abstracted away from the calling class
  • If the socket needs to be passed in then the calling code could possibly modify attributes on the socket which the the ConnectionBroker class is not aware of

What is the proper way of solving this? Am I thinking of something incorrectly?

Android Instrumentation test java.lang.UnsatisfiedLinkError on using AndroidJunitRunner and AndroidJUnit4

I am using robolectric in our unit tests. Recently in our project, we are adding a new dependency from zendesk.

repositories {

maven {
    url 'http://ift.tt/172TP5q'
}

}

compile group: 'com.zendesk', name: 'sdk', version: '1.3.0.1'

Now we have not even referenced any class from this library and we are getting exceptions in our robolectric unit tests just by adding this dependency. I thought the problem is in our project, but its also occurring on a sample robolectric test project.

java.lang.VerifyError: Expecting a stackmap frame at branch target 31 Exception Details: Location: com/zendesk/sdk/power/BatteryStateBroadcastReceiver.onReceive(Landroid/content/Context;Landroid/content/Intent;) V @13: ifnonnull Reason: Expected stackmap frame at this location. Bytecode: 0x0000000: b200 1212 0703 bd00 0fb8 0015 2cc7 0012 0x0000010: b200 1212 0303 bd00 0fb8 0017 a700 66b2 0x0000020: 0012 bb00 1159 b700 1c12 04b6 001d 2cb6 0x0000030: 0014 b600 1db6 001e 03bd 000f b800 1512 0x0000040: 062c b600 14b6 001b 9900 1ab2 0012 1202 0x0000050: 03bd 000f b800 162b b800 1804 b600 19a7 0x0000060: 0023 1205 2cb6 0014 b600 1b99 0017 b200 0x0000070: 1212 0103 bd00 0fb8 0016 2bb8 0018 03b6 0x0000080: 0019 b200 1212 0803 bd00 0fb8 0015 b1

at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.robolectric.internal.Shadow.newInstanceOf(Shadow.java:15)
at org.robolectric.shadows.ShadowApplication.registerBroadcastReceivers(ShadowApplication.java:148)
at org.robolectric.shadows.ShadowApplication.bind(ShadowApplication.java:137)
at org.robolectric.shadows.CoreShadowsAdapter.bind(CoreShadowsAdapter.java:99)
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:121)
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:421)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:234)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:185)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:149)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

How to write a test for an http request that checks the responses returned data?

I have the following method in my AccountsApiHandler module, and I would like write a test that ensures that the accounts are correctly returned. If I am calling this method from one of my tests, how can I retrieve the list of accounts?

AccountsApiHandler.prototype.accounts = function (req, res) {
  var self = this

  /*
   *  Get list of accounts
   */

  if (req.method === 'GET') {
    return self.server.accounts.listAccountAsJson()
      .pipe(JSONStream.stringify())
      .pipe(res);
  }
};

Here is my test, using the hammock npm module to generate my mock request and response objects. This test assumes that the existing accounts are already in the test's database: var test = require('tape') var hammock = require('hammock') var accountsApiHandler = require('../../handlers/accounts-api')()

test('create initial accounts', function (t) {
  request = hammock.Request({
    method: 'GET',
    headers: {
      'content-type': 'application/json'
    },
    url: '/somewhere'
  })
  request.method = 'GET'
  request.end()

  response = hammock.Response()
  var accounts = accountsApiHandler.accounts(request, response)
  console.log("test.accountsApiHandler: accountsApiHandler.accounts: accounts", accounts) // `accounts` is undefined!

  var accountsList = []
  var actualAccounts = getAccountsFromDatabase() // the actual accounts from our db
  accounts
    .on('data', function (data) {
      accountsList.push(data)
    })
    .on('error', function (err) {
      t.fail(err)
    })
    .on('end', function () {
      console.log("results:", accountsList)
      t.equals(accountsList, actualAccounts)
    })

}

When I run this test, my accounts stream is empty, thus giving me an empty list of accounts for accoutnsList. Is there a clean way to get the accounts from my AccountsApiHandler.accounts method?

In Visual Studio 2012, can I run the Memory Allocation Profiler against a unit test?

When I right click on a unit test in VS 2012, there is an option to run the Profiler, but it always runs the performance profiler, not the memory allocation profiler. Is there a way to get it to run the memory profiler instead?

Android Studio Espresso Empty Test Suite

When I run my test method that uses Espresso, it prompts me to choose an emulator, and I pick my existing emulator with my application already started. The emulator subsequently automatically reboots my application, and then displays that that the test suite is empty.

The error

My espresso test case is located in the androidTest folder of the same module as the activity I'm trying to test. I wrote a simple "isDisplayed()" type of a test and right clicked the method and clicked run. I've taken a look at the other questions on Stack Overflow and other resources, but I can't figure out what is causing this problem. The logcat displays nothing and when I tried putting Log.d("debug", "hello hello") in the test method (shown below), nothing shows up in the logcat, nor does anything display when I try putting a System.out.println("hello") in the test method. It seems that although I run the method, none of my code is being run!

Below is some of my build.grade.

apply plugin: 'com.android.application'

android {
   compileSdkVersion 17
   buildToolsVersion "21.1.2"
   defaultConfig {
       applicationId "x"
       minSdkVersion 17
       targetSdkVersion 17
       versionCode 1
       versionName "1.0"

       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }


    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'LICENSE.txt'
    }
}


configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:22.2.0'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

Here is the test case that I'm trying to run.

@RunWith(AndroidJUnit4.class)
public class EspressoTest1 extends ActivityInstrumentationTestCase2<P1>{


    private P1 mActivity;

    public EspressoTest1() {
        super(P1.class);
    }

    public void setUp() throws Exception {

        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
        mActivity = getActivity();

    }

    public void Happy_test() {

        onView(withId(R.id.Btn)).check(matches(isDisplayed()));

    }
}

Test Configuration

And this is the test run configuration.

Any way to conditionally deal with a java UnsatisfiedLinkError?

I have a unit test that is running code for an embedded machine. One of the parts of the class I am testing, but not actively using is a call to some native code for drivers that are only able to be installed on the embedded machine.

Due to this, I get UnsatisfiedLinkError. Each time I try to unit test the program and complains its missing the drivers that are only on the embedded machine.

I suspect the native code is trying to get loaded in the Dynamic Linking part of the JVM initialization.

Since this part is not compiled into the program and instead linked during attempting program execution, can there be any condtional statement added to either the class or the unit test that says basically "hey i am not the embedded machine so don't try to load the native code", or is there no way around this error?

How to run WebServiceProviderFactory IInterfaceAssignmentService and InterfaceAssignment In Unit test?

I created a fonction that verify some rules in fact the fonction is supposed to return a bool whenever element of a list match element of another list

Here is the full code of the Rule Class

  public override TestResult Execute()
    {
        Instrument ins = (Items.Length > 0) ? Items[0] as Instrument : null;
        string errorInfo;

        if (ins == null)
        {
            Result.Message = "Unable to perform test";
            Result.Status = ResultStatus.Error;
            return Result;
        }
        if (MPICSupportDB(ins))
        {
            Result.Message = "DB not supported by MPIC";
            Result.Status = ResultStatus.Yellow;
        }
        else
        {
            Result.Status = ResultStatus.Green;
        }

        return Result;
    }



    private bool MPICSupportDB(Instrument ins)
    {
        IServiceProviderFactory serviceFactory = new WebServiceProviderFactory();
        IInterfaceAssignmentService wService = serviceFactory.CreateInterfaceAssignmentService();
        InterfaceAssignment wAssignments = wService.LoadAssignmentGroup("R4");


        return ins.Connections.OfType<InterfaceConnection>().Where(conn => conn.Card.IsDB).Any(conn => wAssignments.PartMasters.Any(partNumber => (conn.CardPartNumber == partNumber.PartNumber)));


        //foreach (InterfaceConnection conn in ins.Connections.OfType<InterfaceConnection>())
        //    if (conn.Card.IsDB)
        //    {
        //        for (int i = 0; i < wAssignments.PartMasters.Count; i++)
        //            foreach (var partNumber in wAssignments.PartMasters)
        //                if ((conn.CardPartNumber == partNumber.PartNumber))
        //                    return true;
        //    }
        //return false;

    }
}

What I'm exactly looking for is to test this fonction called MPICSupportDB in a unit test

 private bool MPICSupportDB(Instrument ins)
    {
        IServiceProviderFactory serviceFactory = new WebServiceProviderFactory();
        IInterfaceAssignmentService wService = serviceFactory.CreateInterfaceAssignmentService();
        InterfaceAssignment wAssignments = wService.LoadAssignmentGroup("R4");


        return ins.Connections.OfType<InterfaceConnection>().Where(conn => conn.Card.IsDB).Any(conn => wAssignments.PartMasters.Any(partNumber => (conn.CardPartNumber == partNumber.PartNumber))); }

So I created this in my test unit but I'm lost and I have no idea what to do

  [TestMethod]
    public void TestForcompatibleDB()
    {
        var ins = new Instrument();
        var serviceFactoryMock = new Mock<IServiceProviderFactory>();
        var wserviceTest = new Mock<IInterfaceAssignmentService>();
        var wassagnementTest = new Mock<InterfaceAssignment>();

        // adding an MPIC card
        ins.Connections.Add(AddCard(CardType.MPIC, "MA505400612268", "CARD1", 0, ins));

        // adding an MPIC daughterboard
        ins.Connections.Add(AddCard(CardType.GPIM_DB, "MA335022012268", "DB1", 1, ins));


        var rule = new Rule026(RuleApplicability.Test, new object[] { ins });
        var result = rule.Execute();

        Assert.IsNotNull(result);
        Assert.AreEqual(ResultStatus.Green, result.Status);
    }

the problem is that object like Webservice and factoryService object cannot be run directly in a test unit

Can someone help me in how to properly mock these object and make my test run?

How to call public static methods in Unit Test

Hi I have a simple method as following and need to know how I can call it in Unit Test in Visual Studio

 public static bool Test(string value, string regex)
 {
     if (Regex.IsMatch(value, regex, RegexOptions.IgnoreCase))
         return true;

     return false;
 }

here is what I have sofar

 [TestMethod]
 public void TestMethod_Test()
 {
     string value = "myValue";
     string regex = "&#@<>\s\\\$\(\)";

     PrivateType pt = new PrivateType(typeof(myClass));
     bool actualresult = (bool)pt.InvokeStatic("Test", new object[] { value, regex });
     bool expectedResult = false;
     Assert.AreEqual(actualresult, expectedResult);

 }