jeudi 30 avril 2015

Reuse expectations block several times in JMockit

I am writing test cases for a liferay portal in which I want to mock ActionRequest, ThemeDisplay kind of objects. I have tried with writing expectations in each test method.

Now I want to generalize the approach by creating a BaseTest class which provides me all expectations needed for each method so that I don't have to write it again in the all test classes.

For one class I have tried by writing expectations in @Before method. How can I use same in different classes?

For example I want to do following in several classes:

@Before
public void setUp() {

    // All expectations which are required by each test methods
    new Expectations() {{
        themeDisplay.getPermissionChecker();
        returns(permissionChecker);
        actionRequest.getParameter("userId");
        returns("111");
        actionRequest.getParameter("userName");
        returns("User1");
    }};

}

Also is there a way to provide that whenever I call actionRequest.getParameter() it may return the specific value which I provide?

I don't know if this approach is possible or not. Any help will be appreciated.

Unit test the call count of method in then part of a promise in Jasmine and AngularJS

In code below, userService.addPreference is mocked, and so is $state.go, but still the call count of $state.go is always zero. Is there something I may have missed in the setup of userService.addPreference mocked method?

Code that is being unit tested

      userService.addPreference(preference).then(function (dashboard) {
              $state.go('authenticated.dashboard.grid', {id: dashboard.id});
            });

Unit Test Mocked methods and the Unit Test

sinon.stub(userService, 'addPreference', function (preference) {
                var defer = $q.defer();
                defer.resolve(preference);
                return defer.promise;
            });
sinon.stub($state, 'go', function () { });
    it('dashboard.confirm should call $state.go', function () {
        vm.confirm();//this is the function containing code being unit tested
        expect($state.go.callCount).to.equal(1);//this is always ZERO and so failing
    });

Ember-cli unit test using ember-cli-simple-auth

I'm trying to write a unit test for a controller that uses simple-auth authentication in an ajax call. Assertion tests work great but the session property does not appear to be defined in the unit test module scope.

Example action in controller:

authenticate() {
  let credentials = this.getProperties('identification', 'password');
  this.get('session').authenticate('simple-auth-authenticator:token', credentials)
    .then(() => {
      this.transitionToRoute('index');
    }, (error) => {
      this.set('errorMessage', error.error);
    });
}

Example test:

it('should not authenticate', function () {
  let controller = this.subject();
  controller.send('authenticate');
  expect(controller.get('errorMessage')).to.equal("Invalid email/password combination");
});

Session is undefined error message:

TypeError: Cannot read property 'authenticate' of undefined
at authenticate (http://localhost:7357/assets/app.js:587:28)
at mixin.Mixin.create.send (http://localhost:7357/assets/vendor.js:37164:54)
at Context.<anonymous> (http://localhost:7357/assets/app.js:2002:18)
at Context.wrapper (http://localhost:7357/assets/test-support.js:1756:27)
at invoke (http://localhost:7357/assets/test-support.js:13772:21)
at Context.suite.on.context.it.context.specify.method (http://localhost:7357/assets/test-support.js:13837:13)
at Test.require.register.Runnable.run (http://localhost:7357/assets/test-support.js:7064:15)
at Runner.require.register.Runner.runTest (http://localhost:7357/assets/test-support.js:7493:10)
at http://localhost:7357/assets/test-support.js:7571:12
at next (http://localhost:7357/assets/test-support.js:7418:14)

Android Unit Test with Retrofit and Mockito

I separated retrofit api calls methods from the activity code and I want to do a unit test on these methods, one example: The interface:

public interface LoginService {
    @GET("/auth")
    public void basicLogin(Callback<AuthObject> response);
}

and this is the method that do the call, in the main activity I get the object by the event bus.

public class AuthAPI {
    private Bus bus;
    LoginService loginService;

    public AuthAPI(String username, String password) {
        this.bus = BusProvider.getInstance().getBus();
        loginService = ServiceGenerator.createService(LoginService.class,
                CommonUtils.BASE_URL,
                username,
                password);
    }

    public void Login() {

        loginService.basicLogin(new Callback<AuthObject>() {
            @Override
            public void success(AuthObject authObject, Response response) {
                bus.post(authObject);
            }

            @Override
            public void failure(RetrofitError error) {
                AuthObject authObject = new AuthObject();
                authObject.setError(true);
                bus.post(authObject);
            }
        });
    }

}

And here the test

@RunWith(MockitoJUnitRunner.class)
public class AuthCallTest extends TestCase {

    AuthAPI authAPI;

    @Mock
    private LoginService mockApi;

    @Captor
    private ArgumentCaptor<Callback<AuthObject>> cb;

    @Before
    public void setUp() throws Exception {
        authAPI = new AuthAPI("username", "password");
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testLogin() throws Exception {

        Mockito.verify(mockApi).basicLogin((cb.capture()));

        AuthObject authObject = new AuthObject();
        cb.getValue().success(authObject, null);

        assertEquals(authObject.isError(), false);
    }
}

when I launch the test I have this error

Wanted but not invoked:
mockApi.basicLogin(<Capturing argument>);
-> at AuthCallTest.testLogin(AuthCallTest.java:42)
Actually, there were zero interactions with this mock.

What I did wrong, this is driving me crazy I tried to follow this guide without success: http://ift.tt/PojSw5

someone help me :(

Can velocity find tests per package, or do they all have to be at the top level?

The examples I've seen with velocity tests is to put everything in a top level /tests/mocha/MyTest.js, /tests/mocha/OtherTest.js.

I'd like to organize my unit tests into the package they are testing.

E.g.

/my-app
/my-app/packages/my-package
/my-app/packages/my-package/my-package-test.js

In fact, this is the layout that gets created when you run "meteor package create my-package, but I can't figure out how to run my-package-test within the velocity test runner, short of something hackish like symlinking

cd my-app/tests/mocha/client
ln -s ../../packages/my-package/my-package-tests.js

Apart from being annoying to manage these symlinks, this requires exporting anything I'd like to unit test, even though it's not being used in any other packages. Is there a better way?

Implementing Unhandled Exception Handler in C# Unit Tests

I've got some tests and they rely heavily on some shared code that I can't modify. This shared code throws an exception sometimes and I want to be able to handle all uncaught instances of this exception without wrapping every call to the shared code in a try catch (there are years of tests here).

I also want to be able to re-throw the exceptions that aren't of the type that I'm looking for.

I've tried

public void init() 
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Logger.Info("Caught exception");
    throw (Exception)e.ExceptionObject;
}

But it appears that the stock unit test framework (Microsoft.VisualStudio.QualityTools.UnitTestsFramework) is doing something with the AppDomain and preventing me from overriding its UnhandledException handler.

Anyone have any suggestions?

How to test Sequelize 'afterCreate' hook that sends email using nodemailer?

I have a User sequelize model that's loaded using the index.js file in the models directory e.g.

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || "development";
var config    = require(__dirname + '/../../config/database.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
   return (file.indexOf(".") !== 0) && (file !== basename);
 })
  .forEach(function(file) {
     var model = sequelize["import"](path.join(__dirname, file));
     db[model.name] = model;
 });

Object.keys(db).forEach(function(modelName) {
   if ("associate" in db[modelName]) {
   db[modelName].associate(db);
  }
});

 db.sequelize = sequelize;
 db.Sequelize = Sequelize;

 module.exports = db;

In my models afterSave hook:

afterCreate : function(user, options, fn){
  mailer.sendEmailConfirmation(user.email, user.confirmation_code,   function(err){
      if(err){
        console.log(err);
      }
    });

    fn(null, user);
  } 

mailer is a dependency required in the model. How do I go about unit testing this? I basically want to save the user in a mocha test and ensure the sendEmailConfirmation is called.

How to reset a mock invocation counter using Scalatra, Specs2, Mockito

I never expected that I will need to ask a question on this site because everything is already answered normally but with Scalatra... I haven't find a lot of information so here it is:

I'm not experienced with all that so maybe I'm missing something but from what I understand, if I want to test the API that I develop on Scalatra, I need to start the server everytime I run the test suit, right ?

Second question, how can I reset the invocation counter on a method so I don't have to calculate how many times the method has been called since the beginning of the test suite ? Right now using this give me more than one because it counts the previous test.

there was one(*instance*).*method*(*parameter*)

I can still get around the problem by either counting or putting the test as first test for now but it's not a sustainable solution...

Other thing that I found: Reset method on the mock... not found http://ift.tt/1GA9WSW

Isolating the test in a class scope: We need to add

val servlet = new Servlet(eventRepoMock)
addServlet(servlet, "/*")

and we can't repeat the addServlet at every initialization http://ift.tt/1bZEvKf

Last thing that I try is:

servlet.repo = mock[eventRepoMock]

but repo being a value, I can't change it like this.

Neither of these "solutions" feel very clean so I was wondering if someone had a genius idea that can solve that mess !?

Thank you in advance !

MS unit test ( to verify 100 simultaneous requests to server )

In my user interface I have a submit button which submits a request to the server ( thorugh Rest API - say Submit() ) to do some data processing . This works fine . I would like to perform unit test on this ( server data processing code ) to make sure that simultaneous submit requests from different users does not result in any concurrency issues.

How should I go about writing my unit test that would help in verifying that the code works for n simultaneous requests.

My Karma spy is not picking up on my controller function

My spec:

describe('ScheduleController', function() {
    var ScheduleController, scope, spies = {};

    beforeEach(function() {
      module('mapApp');

      return inject(function($injector) {
        var $controller, $rootScope;
        $rootScope = $injector.get('$rootScope');
        $controller = $injector.get('$controller');

        scope = $rootScope.$new()

        $controller('ScheduleController', {
            $scope: scope
        });

        spies.buildScheduleUrl = spyOn(scope, 'buildScheduleUrl').and.callThrough();
      });
    });

    it('should build a schedule url', function() {
        expect(spies.buildScheduleUrl).toHaveBeenCalled();
    });
});

My controller:

window.map.controller('ScheduleController', ['$scope', '$window', 'cache', 'scheduleCache', 'dosingCache', 'patientCache', '$modal', 'util',
    function ($scope, $window, cache, scheduleCache, dosingCache, patientCache, $modal, util) {
        // other stuff here


        $scope.buildScheduleUrl();

    }

]);

So my buildScheduleUrl function does not get called it seems. What am I doing wrong?

How I can stub IDBconnection

I am writting Unit Test for my database connection.

I have following class

    Public class A
        {
            public IDbConnection _dbConnection;

     public A()
     {
        _dbConnection = new SqlConnection(connectionStringName);
      }

            public int ExecuteNoneQuery(CommandDefination command)
            {
               return _dbConnection.Execute(command);
            }
        }

I want to test this class, how I can test with Microsoft Stub/Shim

I have written following code, but it is not working.

 [TestMethod]
        public void TestMethod1()
        {
            StubIDbConnection stubIDbConnection = new StubIDbConnection();
            stubIDbConnection.Execute =(null) => -1;
            var a = new classA();
            int answer = a.ExecuteNoneQuery(null);
            Assert.AreEqual(-1,-1);

         }

how to omit imports using .coveragerc in coverage.py?

I am using nosetests --with-coverage to test and see code coverage of my unit tests. The class that I test has many external dependencies and I mock all of them in my unit test.

When I run nosetests --with-coverage, it shows a really long list of all the imports (including something I don't even know where it is being used).

I learned that I can use .coveragerc for configuration purposes but it seems like I cannot find a helpful instruction on the web.

My questions are.. 1) In which directory do I need to add .coveragerc? How do I specify the directories in .coveragerc? My tests are in a folder called "tests".. /project_folder /project_folder/tests

2)It is going to be a pretty long list if I were to add each in omit= ... What is the best way to only show the class that I am testing with the unittest in the coverage report?

It would be nice if I could get some beginner level code examples for .coveragerc. Thanks.

Hartl Ruby on Rails Tutorial Chapter 12: Tests for the authorization of the following and followers pages - test passed?

I am following the 3rd edition of Hartl's Ruby on Rails Tutorial. In Chapter 12, 12.2.3 Following and followers pages, Listing 12.24: Tests for the authorization of the following and followers pages should be RED according to the book, but I got the test GREEN for some reason.

test/controllers/users_controller_test.rb

require 'test_helper'

class UsersControllerTest < ActionController::TestCase

  def setup 
     @user = users(:user2)
     @other_user = users(:archer)
  end

  test "should redirect index when not logged in" do
    get :index
    assert_redirected_to login_url
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should redirect edit when not logged in" do
    get :edit, id: @user
    assert_not flash.empty?
    assert_redirected_to login_url
  end

  test "should redirect update when logged in" do
    patch :update, id: @user, user: { name: @user.name, email: @user.email }
    assert_not flash.empty?
    assert_redirected_to login_url
  end

   test "should redirect edit when logged in as wrong user" do
    log_in_as(@other_user)
    get :edit, id: @user
    assert flash.empty?
    assert_redirected_to root_url
   end

   test "should redirect update when logged in as wrong user" do
     log_in_as(@other_user)
     patch :update, id: @user, user: { name: @user.name, email: @user.email }
     assert flash.empty?
     assert_redirected_to root_url
   end

   test "should redirect destroy when not logged in" do
      assert_no_difference 'User.count' do
      delete :destroy, id: @user
      end
    assert_redirected_to login_url
   end

   test "should redirect destroy when logged in as an non-admin" do
     log_in_as(@other_user)
     assert_no_difference 'User.count' do
      delete :destroy, id: @user
     end
     assert_redirected_to root_url
   end

  test "should redirect following when not logged in" do
    get :following, id: @user
    assert_redirected_to login_url
  end

  test "should redirect followers when not logged in" do
    get :followers, id: @user
    assert_redirected_to login_url
  end

end

Bellow is the test result:

@rails-tutorial:~/workspace/sample_app (following-users) $ bundle exec rake TEST=test/controllers/users_controller_test.rb
Started

  8/8: [=============================================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.57375s
8 tests, 14 assertions, 0 failures, 0 errors, 0 skips

I noticed that there should be 10 tests with the users_controller_test; however, rake test only tested 8 tests and it looks like the last 2 tests were missing.

Can anyone let me know why?

Thanks in advance!

React unit test with jest in es6

I am pretty new in react world and trying to write simple friendslist application. I wrote my friends store in es6 style and using babel as transpiler from es5 to es6.

import AppDispatcher from '../dispatcher/app_dispatcher';
import { EventEmitter } from 'events';
import FRIENDS_CONST from '../constants/friends';

const CHANGE_EVENT = 'CHANGE';

let friendsList = [];


let add = (name) => {

    let counter = friendsList.length + 1;
    let newFriend = {
        id: counter,
        name: name
    };

    friendsList.push(newFriend);

}

let remove = (id) => {
    let index = friendsList.findIndex(e => e.id == id);
    delete friendsList[index];
}


let FriendsStore = Object.assign({}, EventEmitter.prototype, {

    getAll: () => {
        return friendsList;
    },

    emitChange: () => {
        this.emit(CHANGE_EVENT);
    },

    addChangeListener: (callback) => {
        this.on(CHANGE_EVENT, callback);
    },

    removeChangeListener: (callback) => {
        this.removeListener(CHANGE_EVENT, callback);
    }

});

AppDispatcher.register((action) => {

    switch (action.actionType) {
        case FRIENDS_CONST.ADD_FRIENDS:
            add(action.name);
            FriendsStore.emitChange();
            break;
        case FRIENDS_CONST.REMOVE_FRIENDS:
            remove(action.id);
            FriendsStore.emitChange();
            break;
    }

});

export default FriendsStore;

Now I want to test my store and wrote the unit test also in es6

jest.dontMock('../../constants/friends');
jest.dontMock('../friends_store');


describe('FriendsStore', () => {

    import FRIENDS from '../../constants/friends';
    import AppDispatcher from '../../dispatcher/AppDispatcher';
    import FriendsStore from '../friends_store';

    let FakeAppDispatcher;
    let FakeFriendsStore;
    let callback;

    let addFriends = {
        actionType: FRIENDS.ADD_FRIENDS,
        name: 'Many'
    };

    let removeFriend = {
        actionType: FRIENDS.REMOVE_FRIENDS,
        id: '3'
    };

    beforeEach(function() {
        FakeAppDispatcher = AppDispatcher;
        FakeFriendsStore = FriendsStore;
        callback = AppDispatcher.register.mock.calls[0][0];
    });

    it('Should initialize with no friends items', function() {
        var all = FriendsStore.getAll();
        expect(all).toEqual([]);
    });



}); 

When I execute the test with statement npm test, I've got the error message:

> react-starterify@0.0.9 test /Volumes/Developer/reactjs/app5
> echo "Error: no test specified"

Error: no test specified

What am I doing wrong? The file structure looks as follow: enter image description here

Mockito always return null when testing dropwizard resources

I am trying to test dropwizard resources and followed http://ift.tt/1zhs86A to do so.

However, I always get a null object from the mocked class/method.

The resource method

    @GET
    @Path("/id")
    @ApiOperation("Find property by id")
    @Produces(MediaType.APPLICATION_JSON)
    public Property findById(@QueryParam("id") int id) {

        return propertyDAO.findById(id);
    }

And the test class

public class PropertiesResourceTest {

    private static final PropertiesDAO dao = mock(PropertiesDAO.class);

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new PropertiesResource(dao))
            .build();

    private final Property property = new Property(1);

    @Before
    public void setUp() {

        when(dao.findById(eq(1))).thenReturn(property);
        reset(dao);
    }

    @Test
    public void findById() {
        assertThat(resources.client().target("/properties/id?id=1").request().get(Property.class))
                .isEqualTo(property);
        verify(dao).findById(1);
    }

}

I tried to spin it in many ways, but the result is always the same:

expected:<Property | ID: 1 > but was:<null>

Do you have any leads on why mockito is always returning a null object ?

Do I really need a unit test project for mstest to discover my unit tests?

I want to have the following architecture:

- Stories (folder)
 - CreateUser (class library)
    Dependencies
    View
    ViewModel
    Repository
    Tests

 -  ShareStatusUpdate (class library)
    Dependencies
    View
    ViewModel
    Repository
    Tests

I do not want to create a separate test project for my unit tests. Instead, I would rather couple my test to my class library as a first-class citizen.

Is it possible to add test classes to a class library and have the ability to execute those tests?

How to write tests for writers / parsers? (Python)

I have written a piece of software in Python that does a lot of parsing and a lot of writing files to disk. I am starting to write unit tests, but have no idea how to unit test a function that just writes some data to disk, and returns nothing.

I am familiar with unittest and ddt. Any advice or even a link to a resource where I could learn more would be appreciated.

Unit Testing Web Api Controller that uses IHttpActionResult and ado.net

I'm trying to carry out some unit tests on my API Controller however I'm having issues since it is using IHttpActionResult and my actual data is called from a database (Azure).

Here's a sample of a simple Get by id method

// GET: api/RoundOnesApi/5
    [ResponseType(typeof(RoundOne))]
    public IHttpActionResult GetRoundOne(int id)
    {
        RoundOne roundOne = db.RoundOnes.Find(id);
        if (roundOne == null)
        {
            return NotFound();
        }

        return Ok(roundOne);
    }

I then tried to make a unit test to test this.

 public void TestMethod1()
    {
        //ApplicationDbContext db = new ApplicationDbContext();


        //arrange

        var controller = new RoundOnesApiController();

        //act

        var actionResult = controller.GetRoundOne(1); //1

        //assert

        var response = actionResult as OkNegotiatedContentResult<RoundOne>; //RoundOne is my model class

        Assert.IsNotNull(response);

        Assert.AreEqual(1, response.Content.Id);

GetRoundOne(1) contains a database entry of a football teams information. Since this is not null I assumed it would pass.

By the way I'm just looking to do a general Unit Test to see if GetRoundOne(1) can be tested against actually existing. Once it passes that's all I need.

why am i getting a StackOverflowException when testing a GridViewPager with Robolectric

i'm trying to add a test for the activity in the android wear implementation and getting a stack overflow exception.

the test:

@Test
public void testActivityInit() {
       Robolectric.buildActivity(CustomGridActivity.class).create().start().visible().get();
}

the exception:

java.lang.StackOverflowError at sun.misc.Unsafe.compareAndSwapInt(Native Method) at java.util.concurrent.locks.AbstractQueuedSynchronizer.compareAndSetState(AbstractQueuedSynchronizer.java:566) at java.util.concurrent.locks.ReentrantLock$Sync.nonfairTryAcquire(ReentrantLock.java:137) at java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:370) at java.util.concurrent.ConcurrentHashMap$Segment.put(ConcurrentHashMap.java:432) at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1150) at java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:464) at java.lang.ClassLoader.loadClass(ClassLoader.java:405) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at org.robolectric.internal.bytecode.ShadowWrangler.stripStackTrace(ShadowWrangler.java:331) at org.robolectric.internal.bytecode.RobolectricInternals.cleanStackTrace(RobolectricInternals.java:28) ... at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560) at android.view.View.measure(View.java:17430) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at org.robolectric.util.Scheduler$ScheduledRunnable.run(Scheduler.java:246) at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:167) at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:148) at org.robolectric.util.Scheduler.advanceToLastPostedRunnable(Scheduler.java:111) at org.robolectric.util.Scheduler.unPause(Scheduler.java:42) at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:271) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:311) at org.robolectric.shadows.ShadowViewGroup.addView(ShadowViewGroup.java:35) at android.view.ViewGroup.addView(ViewGroup.java) at android.view.ViewGroup.addView(ViewGroup.java:3709) at android.view.LayoutInflater.rInflate(LayoutInflater.java:810) at android.view.LayoutInflater.inflate(LayoutInflater.java:504) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.wearable.view.WatchViewStub.inflate(WatchViewStub.java:179) at android.support.wearable.view.WatchViewStub.onMeasure(WatchViewStub.java:133) at android.view.View.measure(View.java:17430) at android.support.wearable.view.GridViewPager.measureChild(GridViewPager.java:1363) at android.support.wearable.view.GridViewPager.onMeasure(GridViewPager.java:1334) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:447) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560) at android.view.View.measure(View.java:17430) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)

i've found various reference projects that test android wear, so the basics do work. it seems like the exception is in how the GridViewPager is handled/implemented. has anyone else run in to anything like this or have a fix/workaround?

thanks.

Unit Testing within an RTOS

For my next embedded systems project I want to embrace unit testing. It may not technically be test driven development, but I would at least like to instrument unit tests up front and have comprehensive unit testing.

I am using the IAR EWARM tool chain. I am considering using cmocka, unity, or cunit.

Here's the question: I am going to use an RTOS. I am learning towards using µC/OS-III. How is unit testng going to work with an RTOS in the picture?

Here's my assumtion: In µC/OS-III the entry point is still main. From main you call any init code and then make a call to OSStart() to begin multitasking. So when I am running the test harness I would just not make the call to OSStart()

#ifdef UNIT_TEST
test_runner();
#else
OSStart(&err);
#endif

Then in all of my application code in the tasks I would just need to mock message passing and delay calls to the kernel.

Am I on the right track?

OR

when I am unit testing would it be better to call OSStart(&err) but only setup one task: the test runner.

Javascript unit testing, force error in sinon stub callback

I am trying to test one last bit of this function I cannot seem to hit correctly. Here is the function

CrowdControl.prototype.get = function(callback) {
var options = this.optionsFor('GET');
return q.Promise(function(resolve, reject) {
    callback = callback || function callback(error, response, body) {
        if (error) {
            reject(error);
        } else {
            resolve(body);
        }
    };

    callback();
    request(options, callback);
});
};

And the part I can't seem to hit is

  if (error) {
            reject(error);
        } else {
            resolve(body);
        }

I have the request set as a stub, and here is what I am trying

   it("should call callback, which should reject if errors.", function() {
            var testCallback = testHelpers.stub();
            request.returns("Error");
            crowdControl.get(testCallback);
            //expect(testCallback).to.have.been.called;
            expect(testCallback).to.have.been.calledWith("Error");
        });

Seems like it is not working as I expected, I need to test the callback throwing an error. Thanks!

Structuring procedural code for unit tests

If you're planning to write unit tests for a C program, what is the convention for placement of the main function? Do you put it in it's own separate file, with the functions in another file, that way you can include the functions file inside a test without having conflicts with two main methods? This makes sense to me but just wondering if there's a certain convention.

I ask because we have several SQR programs at work that are a difficult to maintain, and I'd like to take a stab at getting them under test, but I need a way to call the functions from another file, so I figured my first step would be to take the begin-program - end-program section and stick it in a separate file.

Executing test from another test in google test framework

Let's say I have two tests in the same testcase: writeTest and readTest

TEST_F(testcase, writeTest)
{
  ASSERT_EQ(OK, write_something();
} 

TEST_F(testcase, readTest)
{
  ASSERT_EQ(OK, write_something();
  ASSERT_EQ(OK, read_something();
}

My question is, can I execute writeTest from readTest?

To read something there must be something written. So I want to execute the writeTest (while being in test code of readTest) rather than repeating the codes of writeTest?

This is specially important when there is huge line of code in the writeTest.

Android NDK JNI Unit Test

Is there a way to test my NDK code, exposed via a JNI class? I'm using Android Studio + Gradle and Robolectric for my other tests.

I found some thread that offers a solution for this problem for Robolectric 1.2, but nothing on how I can get this working on 2.+. Preferably, I'd like to actual test the real NDK code w/o mocks or stubs, since the output from that is very critical.

Mock in multithreading context for testing in Python

In a Django project, I would like to write a test for a function that is used in a multiprocessing context (Processing.create_all_files). If I were using a single thread, I would do 'mock' in order to check the parameters used for calling a given function (FileCreator.create in my case).

However, once the function FileCreator.create is called by a multiprocessing.Pool, mock does not work anymore with it.

How should I do my test for create_all_files? Thanks.

test_program.py:

def test_create_all_files(self):
    file_paths = [ (...) ] # Initialize file_paths
    processing = Processing()
        with mock.patch('FileCreator.create', return_value=True) as create:
            with mock.patch('os.path.isfile', return_value=False):
                processing.create_all_files()
                calls = create.call_args_list

        for file_path in file_paths:
            self.assertTrue(((file_path),) in calls)


program.py

def unwrap_self_create_one_file(arg):
    return Processing.process_one_file(*arg)

class Processing:
    (...)

    def create_one_file(self, file_path):
       if os.path.isfile(file_path):
        FileCreator.create(file_path) # CREATE FILE

        def create_all_files(file_paths):
       (...) # define args_lst considering file_paths
       ncpus = 4
           pool = multiprocessing.Pool(ncpus)
           pool.map(unwrap_create_one_file, args_lst, chunksize=1)

JUnit assertion to force a line to be executed

Is there any junit assertion, with which i can force a line to be executed?

For example:

doAnswer(new Answer<Void>() {
    @SuppressWarnings("unchecked")
    @Override
    public Void answer(final InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        Map<String, String> fieldMapActual = (Map<String, String>) arguments[0];
        assertEquals(fieldMap, fieldMapActual);

        **assertFailIfThisLineIsNotExecuted();**

        return null;
    }
}).when(x).myMethod(xxx);

As i simulate the behaviour of myMethod, the method answer from the anonymous inner type will be executed at runtime of the myMethod (not at runtime of junit test), if myMethod will be called with the intended value/parameter. In order to assert that the method is called, i must additionally define a verify (otherwise my test would still run even if the method is not called).

verify(x).myMethod(xxx); 

If i had a chance to write sth like assertFailIfThisLineIsNotExecuted in the answer method, i would not have to define an extra verify. So again, Is there any junit assertion, with which i can force a line to be executed?

Boost.Tests where is entry point?

I'm using JetBrain's CLion and try to run some boost tests, but they won't. Here's my code:

#define BOOST_TEST_MAIN 1
#define BOOST_TEST_MODULE !
#include <boost/test/unit_test.hpp>
#include <iostream>

BOOST_AUTO_TEST_CASE(MyTest) {
    BOOST_CHECK(false);
}


int main() {
    std::cout << "in main!" << std::endl;
    return 0;
}

and my cmake file :

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
set(BOOST_ROOT /home/vitalii/Downloads/boost_1_57_0)
find_package(Boost 1.57 COMPONENTS unit_test_framework REQUIRED)
add_executable(justForFun ${SOURCE_FILES})
if (Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    link_directories(${Boost_LIBRARY_DIRS})
    target_link_libraries(justForFun ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})
else()
    message(FATAL "Boost not found")
endif()
enable_testing()

The problem is that the output wil be just "in main". And test won't launch. I figured i don't need 'main' function. It should be created automatically. But If i delete it then I get these errors :

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

Can someone please help me ?

Smart Unit Tests standalone

I've been working with Smart Unit Tests (formerly Pex) for some time now. Pex had the ability to run as a standalone, command-line application which was really useful for several scenarios (e.g. extending the list of parameters of the Parameterized Unit Tests).

However, in the case of Smart Unit Tests (integrated in VS2015), I was not able to find a function to run it standalone (it only works with right clicking on the method to be analyzed). So, for example, when I want to extend the list of PUT parameters, I have to do it also in the method under test (which I really want to avoid) in order have it discovered by Smart Unit Tests.

So, my question is, that are there any possibilities to run Smart Unit Tests only from the generated PUT method like it was in Pex?

Angularjs Jasmine Unit Test

I copied the angularjs example for unit testing from here. As its just direct implementation of the example, i am confused with the error thrown.

I work in Linux and using Brackets to as IDE.

Please let know what is the missing element to run the jasmine tests.

Ouput of Jasmine

PasswordController encountered a declaration exception.       
ReferenceError: module is not defined

controller.js

angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
  $scope.password = '';
  $scope.grade = function() {
    var size = $scope.password.length;
    if (size > 8) {
      $scope.strength = 'strong';
    } else if (size > 3) {
      $scope.strength = 'medium';
    } else {
      $scope.strength = 'weak';
    }
  };
});

controller-spec.js

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

karma-conf.js

 // list of files / patterns to load in the browser
    files: [
            'bower_components/angular/angular.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'bower_components/angular-resource/angular-resource.js',
             'app/controllers/*.js',
            'test/controllers/*.js'
    ],

mercredi 29 avril 2015

In JavaScript Unit Testing, test same kind of data but get different result

this is my project directory :

QQ20150430-1@2x.png

i'm making a projcet for fetch info from website and write into file as json

when i use 'fs-extra' module to check the content of file , i get different result:

QQ20150430-2@2x.png

it's pretty weird , if i am got a wrong path for check file's content , those three unit testing case must fail together , but the first one pass !

unit testing log:

QQ20150430-3@2x.png

i use an object to config the path :

var config = {
    promiseData:    '../data/promiseData.json',
    asyncData:      '../data/asyncData.json',
    eventproxyData: '../data/eventproxyData.json'
}

and the data file all in the same directory , why the unit testing case only pass the first one ??

and then i try to use the readJson() and readJsonSync(), the result as before , only the first pass .

there are three same content in the file

and i'm confused and please help me , thanks a lot ~

the project address: callback

how jMockIt StrictExpectations work

I am relatively new with the jMockIt framework which I started using a few months ago on a personal project with a view of adapting it in one of our enterprise projects. So far it looks promising and it looks like a good alternative for our Mockito + Powermock combination that we have in place at the moment. This statement should not be read as I am not advocating for simplicity but not being obliged to compromise your design just for the sake of making things easier to test it is definitely very appealing.

In my view one other appealing thing was the availability of the Strict Expectations. The way I understood this concept was that if I have the class under test using multiple mocked collaborators then not setting the exact interactions with those mocked collaborators will cause the test to fail. In reality this does not seem to happen. It seems to me that in order for a mocked collaborator to have its interactions monitored you need to have at least one expectation set against that mocked collaborator.

When I realized this I felt a bit disappointed as it can easily lead to untested code when adding new collaborators. Hope my approach is not the right one and someone on here will be able to put me on the right direction. I put together a short test case to make it easier to reproduce what I am saying.

package my.testing.pkg;

import mockit.Mocked;
import mockit.StrictExpectations;
import mockit.Verifications;
import mockit.integration.junit4.JMockit;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

@RunWith(JMockit.class)
public class LoggerTest {
    class ClassUnderTest {
        private final Logger logger = Logger.getLogger(ClassUnderTest.class);
        String getString() {
            logger.debug("about to return a string");
            return "xyz";
        }
    }

    @Mocked
    private Logger logger;

    @Test
    public void shouldReturnTheRightString() throws Exception {
        new StrictExpectations() {{
        }};
        assertEquals("xyz", new ClassUnderTest().getString());
        new Verifications() {{
            logger.debug("about to return a string");
        }};
    }
}

The above unit test passes. It also passes if you comment out the whole verification block or if you do not have a verification block and move the logger interaction in the expectations block. What I expected was that if I have a mocked logger and there were interactions with that logger then the missing of either a strict expectation or a verification entry related to that logger will cause my test to fail.

Thank you in advance for any clarification.

How to execute F# unittest code with F# interpreter (fsharpi)?

I have this F# unit test code (testit.fsx) from http://ift.tt/1lHkOEP

#r @"/Users/smcho/Dropbox/smcho/bin/mono/NUnit.2.6.4/nunit.framework.dll"
open NUnit.Framework

[<TestFixture>]
type TestClass() = 

    [<Test>]
    member this.When2IsAddedTo2Expect4() = 
        Assert.AreEqual(4, 2+2)

I'm trying to run the test with fsharpi, but when I executed fsharpi testit.fsx I get no output.

I use Mono on Mac OS X.

System.ComponentModel.Win32Exception when executing F# Nunit unit test code with Mono

I'm trying to use F# unittest on Mono. I use Mac OS X. I have the following environments

nunitFramework=.../bin/mono/NUnit.2.6.4/nunit.framework.dll
console=.../bin/mono/NUnit.2.6.4/nunit-console.exe
fsUnit=.../bin/mono/NUnit.2.6.4/FsUnit.NUnit.dll

This is F# code:

namespace HelloWorld.Core
module Hello = let SayHello name = "Hello"

This is the unittest for it.

module HelloWorld.Tests.Hello  
open HelloWorld.Core.Hello
open NUnit.Framework
open FsUnit

[<Test>]
let shouldSayHello () = Assert.AreEqual("Hello World!", SayHello "World")

I compile the code and unittest:

fsharpc --target:library HelloWorld.fs
fsharpc --target:library -r:HelloWorld.dll -r:$nunitFramework -r:$fsUnit HelloWorldTest.fs

I run the test: mono $console HelloWorldTest.dll to get the error messages.

ProcessModel: Default    DomainUsage: Single
Execution Runtime: mono-3.5
Unhandled Exception:
System.ComponentModel.Win32Exception: ApplicationName='mono', CommandLine='--runtime=v4.0.30319 "/Users/smcho/Dropbox/smcho/bin/mono/NUnit.2.6.4/nunit-agent.exe" cc695a32-96df-4346-bfda-e5547d7acc87 tcp://127.0.0.1:58755/TestAgency', CurrentDirectory='', Native error= Cannot find the specified file
  at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0 
  at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0 
  at System.Diagnostics.Process.Start () [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:Start ()
  at NUnit.Util.TestAgency.LaunchAgentProcess (NUnit.Core.RuntimeFramework targetRuntime) [0x00000] in <filename unknown>:0 
  at NUnit.Util.TestAgency.CreateRemoteAgent (NUnit.Core.RuntimeFramework framework, Int32 waitTime) [0x00000] in <filename unknown>:0 
  at NUnit.Util.TestAgency.GetAgent (NUnit.Core.RuntimeFramework framework, Int32 waitTime) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) NUnit.Util.TestAgency:GetAgent (NUnit.Core.RuntimeFramework,int)
  at NUnit.Util.ProcessRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0 
  at NUnit.ConsoleRunner.ConsoleUi.Execute (NUnit.ConsoleRunner.ConsoleOptions options) [0x00000] in <filename unknown>:0 
  at NUnit.ConsoleRunner.Runner.Main (System.String[] args) [0x00000] in <filename unknown>:0 

What might be wrong?

How to stub CocoaLumberjack or NSLog with OCMockito

I can stub/verify a class method, but I'm having difficulty with defined macros. I'm trying to test that one of my methods calls DDLogInfo.

It's defined like so in the CocoaLumberjack source

#define DDLogInfo(frmt, ...)    LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagInfo,    0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__)

thanks!

Unit testing a Django BoundField

I have a form that a user submits that has a lot of processing on the back end. In that processing, I create a dictionary:

def function_that_returns_form_data(form, ...):
    form_data = {'account' : form['account'], ...}
    return form_data

My unit test testing the function which returns the dictionary looks something like:

self.form = PaymentForm(data=...)
returned_dict = function_that_returns_form_data(self.form, ...)
expected_dict = {'account' : self.form['account'], ...}

self.assertEqual(expected_dict, function_returning_form_data)

All the items in returned_dict and expected_dict match except for 'account', which causes an error:

AssertionError: Lists differ: ... First differing element 0: {'account': <django.forms.forms.BoundField object at 0x043E6F50>, ... {'account': <django.forms.forms.BoundField object at 0x043E64B0>, ...

I'm POSITIVE that these objects are the same, and I want to pass along the object instead of pulling out all of its fields individually. How can I get Django to test a bound field with a normal comparison (of the field's value) instead of comparing the location of the object in memory?

how do you test private static method in module in python

we have a module of static methods in our python app. these methods use a lot of private (e.g: "__do_sub_task2(**args)") I would like to write unit tests for these private static methods within this module, but I am getting refernce errors.

is there a way to do this?

update: adding scenario

I have a module file named 'my_module.py' contents of said file is as follows:

def public_method_foo(my_number):
  return __sub_method_bar(my_number * 10)

def __sub_method_bar(other_number)
  return other_number + 11

Angular testing http request error

I am trying to test a http request with dynamic url

I have something in my service file like

My service file.

//other service codes..
//other service codes..

return $http.get('/api/product/' + id + '/description')
//id is dynamic 

Test file

describe('test', function () {
    beforeEach(module('myApp'));

    var $httpBackend, testCtrl, scope;

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        testCtrl = _$controller_('testCtrl', {
            $scope: scope
        });
    }));

    it('should check the request', function() {
        $httpBackend.expectGET('/api/product/12345/description').respond({name:'test'});
        $httpBackend.flush();
        expect(scope.product).toBeDefined();
    })
});

I am getting an error saying

Error: Unexpected request: GET /api/product/description

I am not sure how to test the dynamic url. Can anyone help me about it? Thanks a lot!

Can an abstract class be mocked using mockito?

In a class under test, if its constructor takes in an abstract class parameter can we mock it using mockito?

Ex

public abstract AbstractClass{
} 

//Class under test
public class SourceClass{            
  SourceClass(AbstractClass abstractClass){}            
}

@RunWith(MockitoJUnitRunner.class
public SourceClassTest{
 @Mock
  AbstractClass abstractClass;
}

whenever I do this i get this error

java.lang.ExceptionInInitializerError

Ther version of mockito I am using i 1.8.5

how to test the service in the app

I am trying to test the factory for Angular..

my Service file

angular.module('myApp').factory('testService', ['$resource', function ($resource) {
    return $resource(
        '/api/product:id',
        { id: '@id'},
        {
            'query': {
                url: '/api/v0.1/item/:itemId',
                method: 'GET'
            }            
        }
    );
}]);

my test file

describe('Factory test', function () {
    beforeEach(module('myApp'));
    var $httpBackend, $rootScope, mockData;

    beforeEach(inject(function (_$rootScope_, _$httpBackend_, _testService_) {
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        mockData = _testService_;   
    }));

    it('should return data', function() {
        $httpBackend.expect('GET','/api/product/').respond(200,'success');
        var result = mockData.$query(); .//getting error here. 'undefined is not a function'
        $httpBackend.flush();
        expect(result).toBeDefined();
    })
})

I am not sure how to test the testService call. Can anyone help me about it? Thanks a lot!

Javascript unit tesing, test hitting a callback inside function

I am having trouble getting complete coverage in my testing where I am trying to hit a callback function inside the function I am testing. Here is the function :

CrowdControl.prototype.get = function() {
    var options = this.optionsFor('GET');
    return q.Promise(function(resolve, reject) {
        function callback(error, response, body) {
            if (error) {
                reject(error);
            } else {
                resolve(body);
            }
        }

        request(options, callback);
    });
};

So I have the function covered off except the function callback :

function callback(error, response, body) {
    if (error) {
        reject(error);
    } else {
        resolve(body);
    }
}

I cant seem to figure out how to hit this with tests.

Up top I have the request stubbed out like this

   var request = sinon.stub();

beforeEach(function() {
    CrowdControl = rewire('crowdcontrol');
    CrowdControl.__set__({
        request: request
    });
});

So I'm not sure how I can make it hit the callback and test that. Could use some insight as this is still new to me. Thanks!

So I'm trying a simple test at first something like this -

 it("should call callback function.", function() {
        crowdControl.get();
        //callback should fire?
        expect(callback).to.have.been.called;

    });

How can memoized functions be tested?

I have a simple memoizer which I'm using to save some time around expensive network calls. Roughly, my code looks like this:

# mem.py
import functools
import time


def memoize(fn):
    """
    Decorate a function so that it results are cached in memory.

    >>> import random
    >>> random.seed(0)
    >>> f = lambda x: random.randint(0, 10)
    >>> [f(1) for _ in range(10)]
    [9, 8, 4, 2, 5, 4, 8, 3, 5, 6]
    >>> [f(2) for _ in range(10)]
    [9, 5, 3, 8, 6, 2, 10, 10, 8, 9]
    >>> g = memoize(f)
    >>> [g(1) for _ in range(10)]
    [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
    >>> [g(2) for _ in range(10)]
    [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
    """
    cache = {}

    @functools.wraps(fn)
    def wrapped(*args, **kwargs):
        key = args, tuple(sorted(kwargs))
        try:
            return cache[key]
        except KeyError:
            cache[key] = fn(*args, **kwargs)
            return cache[key]
    return wrapped


def network_call(user_id):
    time.sleep(1)
    return 1


@memoize
def search(user_id):
    return network_call(user_id)

And I have tests for this code, where I mock out different return values of network_call() to make sure some modifications I do in search() work as expected.

import mock

import mem


@mock.patch('mem.network_call')
def test_search(mock_network_call):
    mock_network_call.return_value = 2
    assert mem.search(1) == 2


@mock.patch('mem.network_call')
def test_search_2(mock_network_call):
    mock_network_call.return_value = 3
    assert mem.search(1) == 3

However, when I run these tests, I get a failure because search() returns a cached result.

CAESAR-BAUTISTA:~ caesarbautista$ py.test test_mem.py
============================= test session starts ==============================
platform darwin -- Python 2.7.8 -- py-1.4.26 -- pytest-2.6.4
collected 2 items

test_mem.py .F

=================================== FAILURES ===================================
________________________________ test_search_2 _________________________________

args = (<MagicMock name='network_call' id='4438999312'>,), keywargs = {}
extra_args = [<MagicMock name='network_call' id='4438999312'>]
entered_patchers = [<mock._patch object at 0x108913dd0>]
exc_info = (<class '_pytest.assertion.reinterpret.AssertionError'>, AssertionError(u'assert 2 == 3\n +  where 2 = <function search at 0x10893f848>(1)\n +    where <function search at 0x10893f848> = mem.search',), <traceback object at 0x1089502d8>)
patching = <mock._patch object at 0x108913dd0>
arg = <MagicMock name='network_call' id='4438999312'>

    @wraps(func)
    def patched(*args, **keywargs):
        # don't use a with here (backwards compatability with Python 2.4)
        extra_args = []
        entered_patchers = []

        # can't use try...except...finally because of Python 2.4
        # compatibility
        exc_info = tuple()
        try:
            try:
                for patching in patched.patchings:
                    arg = patching.__enter__()
                    entered_patchers.append(patching)
                    if patching.attribute_name is not None:
                        keywargs.update(arg)
                    elif patching.new is DEFAULT:
                        extra_args.append(arg)

                args += tuple(extra_args)
>               return func(*args, **keywargs)

/opt/boxen/homebrew/lib/python2.7/site-packages/mock.py:1201:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

mock_network_call = <MagicMock name='network_call' id='4438999312'>

    @mock.patch('mem.network_call')
    def test_search_2(mock_network_call):
        mock_network_call.return_value = 3
>       assert mem.search(1) == 3
E       assert 2 == 3
E        +  where 2 = <function search at 0x10893f848>(1)
E        +    where <function search at 0x10893f848> = mem.search

test_mem.py:15: AssertionError
====================== 1 failed, 1 passed in 0.03 seconds ======================

Is there a way to test memoized functions? I've considered some alternatives but they each have drawbacks.

One solution is to mock memoize(). I am reluctant to do this because it is an implementation detail. Theoretically, I should be able to memoize and unmemoize functions without the rest of the system, including tests, noticing from a functional standpoint.

Another solution is to rewrite the code to expose the decorated function. That is I could so something like this:

def _search():
    return 1
search = memoize(_search)

However, this runs into the same problems as above, although it's arguably worse because it will not work for recursive functions.

Is there a shorter way to mock an object in jasmine?

I have an angular filter function that relies on a $window function that has a very big namespace:

.filter('dbNonUtcToDate', function ($window) { //for fields like birthdate in EmployeeData which are not UTC
    return function (val, defaultVal) {
        if (val !== null) {

            var mdate = $window.moment($.jsonDateToDate(val)).format($window.Fr.Alpha.Rep.Web.context.dateFormat().toUpperCase());
            var nullMDate = $window.moment([1, 0, 1]).format($window.Fr.Alpha.Rep.Web.context.dateFormat().toUpperCase());
            if (mdate !== nullMDate) {
                return mdate;
            }
        }
        return defaultVal !== undefined ? defaultVal : '';
    };
})

Is there a way to mock the $window.Fr.Alpha.Rep.Web.context.dateFormat() without doing something like:

beforeEach(module(function ($provide) {
    var fakeWindow = {
        Fr:
        {
            Alpha:
            {
                Rep:
                {
                    Web:
                    {
                        context:
                        {
                            dateFormat: function () {
                                return ...;
                            }
                        }
                    }
                }
            }
        }
    }

    $provide.value('$window', fakeWindow);
}));

How to write a test in Jasmine where the object's existence is checked prior to the function call on that object?

It's easiest to describe the problem by showing a code sample.

Code under test:

function something() {
    if(this.myObject) {
        this.myObject.callMyFunction();
    }

    this.callAnotherFunction();
}

Jasmine test:

it("should call myObject.callMyFunction() because 'myObject' is defined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.something();
    expect(theScope.myObject.callMyFunction).toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST PASSES

it("should call not myObject.callMyFunction() because 'myObject' is undefined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.myObject = undefined;
    theScope.something();
    expect(theScope.myObject.callMyFunction).not.toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST FAILS

As you can see in the second test, I'm trying to set theScope.myObject to be undefined, but the test won't run because it's then calling callMyFunction() on the undefined object theScope.myObject.

Mockito @InjectMocks doesn't work for fields with same type

I was very surprised to find out that following simple code example doesn't work for all Mockito versions > 1.8.5

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {

    @Mock(name = "b2")
    private B b2;

    @InjectMocks
    private A a;

    @Test
    public void testInjection() throws Exception {
        assertNotNull(a.b2); //fails
        assertNull(a.b1); //also fails, because unexpectedly b2 mock gets injected here
    }

    static class A{
        private B b1;
        private B b2;
    }

    interface B{}
}

In javadocs (http://ift.tt/1dWJCnO) there is a quote:

Note 1: If you have fields with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen.

Does it mean that if I have several fields with same type I can't mock ONLY ONE of them but rather should define @Mocks for ALL fields with same type? Is it known limitation and is there any reason why it wasn't fixed yet? It should be straightforward to match @Mocks by fields names, isn't it?

Using mock to patch a non-existing attribute

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

Simplified example of objects I want to patch.

class MyClass(object):
    def __getattr__(self, attr):
        if attr == 'myfunc':
            return lambda:return None
        raise AttributeError('error')


class MyContextManager(object):
    def __init__(self):
        super(MyContextManager, self).__init__()
        self.myclass = MyClass()

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.myclass.myfunc()

Test code

def test_MyContextManager():
    with patch.object(MyClass, 'myfunc', return_value=None) as mock_obj:
        with MyContextManager():
             pass

    # Do some tests on mock object

Here is the error I get:

AttributeError: <class 'MyClass'> does not have the attribute 'myfunc'

I'm able to do this and run the test, but it doesn't restore the attribute (or simply remove the mock attribute in this case) automatically:

MyClass.myfunc= Mock(return_value=None)

I'm open to using another library besides mock to achieve this. I'm also using pytest.

getRequests() must return an Iterable of arrays

my code:

@RunWith(Parameterized.class)                                                                              
public class FreshResultCompareRunner2 {                                                                   


    //This is called before @BeforeClass !                                                                 
    @Parameterized.Parameters                                                                              
    public static Collection getRequests() throws IOException {                                            
        injector = Guice.createInjector(new MainModule());                                                 
        initStaticFromInjector();                                                                          
        initTestInput();                                                                                   
        return OrganizeTestParameterizedInput();                                                           
    }                                                                                                      


    private static void initTestInput() throws IOException {                                               

    }                                                                                                      

    private static Collection OrganizeTestParameterizedInput() {                                           

        Object[] objectMatrix = new Object[100];                                                
        for (int i = 0; i < 100; i++) {                                                         
            objectMatrix[i] = i;                                                                           
        }                                                                                                  
        return Arrays.asList(objectMatrix);                                                                
    }                                                                                                      

returns the following exception:

getRequests() must return an Iterable of arrays

how can i run the parameterized junit with increasing int only as input param?

say run the same test for i=0 ...100 ?

Static analysis dispose warning in test class when object is disposed in test cleanup

I have a lot of test classes like this.

[TestClass]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public class TestClass
{
    private IDisposable _disposable;

    [TestInitialize]
    public void TestInitialize()
    {
        _disposable = //new disposable object...;
    }

    [TestCleanup]
    public void TestCleanup()
    {
        _disposable.Dispose();
    }

    [TestMethod]
    public void Test1()
    {
        //Uses _disposable
    }

    [TestMethod]
    public void Test2()
    {
        //Uses _disposable
    }

    [TestMethod]
    public void TestN()
    {
        //Uses _disposable
    }
}

Static analysis with FxCop results in the following warning because I do not implement the dispose pattern on my test class.

"CA1001: Types that own disposable fields should be disposable"

Right now I just suppress the message in the source, but I feel like there has to be a better way than cluttering all my tests with SuppressMessageAttribute. This seems like it would be a common pattern in testing - create object for the test and then dispose it after the test. I cannot just implement IDisposable on the test class because only one test object is created for all test methods. I want to dispose this object between every test method.

I know I could create the object in each test and dispose it in the test, but I'd rather continue to use SuppressMessageAttribute over copying and pasting the same code into each test method. It seems like the lesser of the two evils. Is there a better way to create a disposable object before each test and dispose it after each test that doesn't result in warning CA1001?

Thanks for the help in advance.

Simulate Button click in View Controller for unit tests Xcode

I have created a Tennis Scorer app in Xcode and I'm now creating unit tests for the app.

When player 1 scores a button is pressed and when player 2 scores a different button is pressed.

How can I simulate these button clicks in my unit tests which are in a separate class?

I can run methods in other classes but cannot connect to the view controller to run methods/button clicks. How can I do this?

Thanks

Unit Testing a PHP Script

I have some php scripts that are run as cronjobs. No classes and only a few functions.

Id like to test the script with PHPUnit to make sure everything is working but it appears I need to rewrite the php as a class, which I dont want to do (or know how to).

For example if I had a script and its only function was to add 1 and 2 together,

 <?php

 $a=1;
 $b=2
 $c=$a+$b;

 ?>

how do I test that $c==3 with phpunit?

Thanks, Don

Unknown Provider when testing a modal dialog

Preface : I'm quite new to Angular and very new to unit-testing. Be gentle.

I'm trying to run unit tests on a controller for a bootstrap modal window.

When initiating the modal I am passing through an object called thisVersion like so :

 function showShareDialog(thisVersion){
        var modalInstance = $modal.open({
            templateUrl: 'app/shares/views/shares-dialogue.tpl.html',
            controller: 'SharesCtrl',
            resolve:{
                thisVersion:function(){
                    return thisVersion;
                }
            }
        });
        modalInstance.result.then(function (validated) {
            // .. more code
        });
    }    

As soon as the Shares Controller is instantiated I am calling a method on thisVersion

thisVersion.getList('shares').then(function(result){
    $scope.shares = result;
});

thisVersion is being passed in to the controller as a dependency, and that all works as expected.

The issue, however, is that I can't seem to inject it into my test suites. I keep getting this error

Error: [$injector:unpr] Unknown provider: thisVersionProvider <- thisVersion

This is (most of) my test suite :

var scope, controller, thisVersion;

  beforeEach(module('app'));
  beforeEach(inject(function ($controller, $rootScope, _thisVersion_) {

        scope = $rootScope.$new();       
        controller = $controller('SharesCtrl', {
            $scope: scope
        });
        thisVersion = _thisVersion_;

    }));

 it('should get a list of all shares',  function(){
     expect(thisVersion.getList).not.toBe('undefined');
 });

I know I am going to have to mock the call to the Api from thisVersion.getList() but for now I'm just concerned with getting the test suite to recognise thisVersion

Unit test for Spring boot Hibernate JPA based DAOs

I am trying to write unit tests for my Spring Boot based application that uses Hibernate/JPA entities & DAOs. Here are the steps I’ve followed so far:

1) Added following to pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

2) In ../test/resources/application.properties, I’ve added this:

spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url: jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password =

3) In ../test/resources/import.sql I’ve added a few ‘insert into…’, data creation scripts.

insert into groups(GROUP_NAME, THREAD_POOL_SIZE) values ("TEST GROUP 1", 5);

4) The unit test looks like this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)

public class TestGroupDao {

    @Autowired
    GroupDao groupDao;

    @Test
    public void testFindByName() {

        Group group = groupDao.findByName("TEST GROUP 1");
        //assertThat(group.getPoolSize(), is(equalTo(5)));
    }
}

When I run this Test, I get error messages such as:

org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table..
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: user lacks privilege or object not found: PUBLIC.GROUP

What am I missing?

Teamcity and Unit Testing Windows Store apps

I've been struggling to make Teamcity 9 compile and run Unit Tests for my Visual Studio solution.

I have a Windows Phone 8.1 (WinRT, not silverlight) project and a "MyProject.Common.dll" portable class library with common functionality.

I created a "Windows Phone Unit Test App" project. If i run it from VS, it runs on the emulator and runs my unit tests. All is Ok.

If i want to run the unit tests from a console i use this command:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe MyProject.Tests_1.0.0.1_x86.appx /InIsolation /settings:RunOnEmu.runsettings"

It works. It launches the emulator, deploys the appx and run unit tests.

Now the problem: using Teamcity 9, i configure a command line build step runner using the same command , and i get this error:

Error: Could not start test run for the tests for Windows Phone app: Unit tests for Windows Store apps cannot be run from a service or non interactive process. Please run unit tests from an interactive process..

Is there a way to bypass this error?

How to access object instance from mocked instance method

In the code below where it says foo_obj = ????, how can I get a reference to the Foo object instance, or what could be a better approach?

class Foo(object):

    def __init__(self):
        self.hello = "Hey!"

    def bar(self):
        return self.hello + " How's it going?"

def side_effect_foo_bar(*args, **kwargs):
    foo_obj = ????
    return foo_obj.hello + " What's up?"

class TestFoo(unittest.TestCase):

    @patch.object(Foo, 'bar')
    def test_bar(self, mocked_bar):
        mocked_bar.side_effect = side_effect_foo_bar
        foo = Foo()
        self.assertTrue(foo.bar() == "Hey! What's up?")

Can't use DB Transactions in Controllers in laravel (DB::beginTransaction)

I have a DoctorsController which has a store method. I'm testing this method and I want my Models not to INSERT their data in testing environment. So I'm using DB::beginTransaction , DB::rollback() , DB::commit() methods in my controllers and my testing method to prevent INSERT queries. my problem is => Database is having records while my tests are running. I don't want any INSERTS during tests.

My test code :

public function testStoreMethod()
{
    /*
     * Test when validation fails
     */
    $data = include_once('DoctorsControllerFormData.php');

    foreach($data as $item){
        DB::beginTransaction();
        $response = $this->call('POST', 'doctors', $item);
        $this->assertResponseStatus(400, "response's HTTP code is not 400 : " . implode('\n',array_flatten($item)));
        Log::debug($response);
        DB::rollback();
    }
}

My DoctorsController code snippet : (which calls UsersController's store method)

public function store()
{
    //some code
    DB::beginTransaction();
    try{
        /*
         * User Creation
         */
        $user = new UsersController();
        $user->setResource('doctor');
        $userID = $user->store();

        //some other code
    }catch (InputValidationFailedException $e){
        DB::rollback();
        return Response::make(json_encode(array('error' => $e->getErrors())), \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
    }catch(Exception $e){
        Log::error('Server Error at DoctorsController');
        DB::rollback();
        App::abort(500, $e->getMessage());
    }
}

My UsersController code snippet :

public function store()
{
    $user = new User;

    try{
        $inputs = Input::all();
        Log::info("input Data" . implode("\n", array_flatten(Input::all())));
        /*
         * User Creation
         */
        $v = Validator::make(
            $inputs,
            User::$rules
        );

        if($v->fails()) {
            Log::error('Validation Failed! ' . implode("\n", array_flatten($v->messages()->all())));
            throw new InputValidationFailedException($v);
        }
        $user->fname = Input::get('fname');//set first name
        $user->lname = Input::get('lname');//set last name
        $user->email = Input::get('email');//set email
        $user->cell = Input::get('cell');//set cell number
        $user->password = Hash::make(Input::get('password'));//set password
        $user->gender_id = Input::get('gender') == 'm' ? 1 : 0;//set gender
        $user->is_active = 0;//set activation status
        $user->role_id = ($this->resource == 'doctor') ? 1 : 2;
        $user->activation_time = 0;//set activation time default to 0
        $user->expiration_time = 0;//set expiration time default to 0
        //insert the user into DB
        $user->save();
    }catch (InputValidationFailedException $e){
        Log::info('User Validation Failed! ' . implode("\n", array_flatten($e->getErrors())));
        throw $e;
    }catch (Exception $e){
        Log::error('Server Error at UsersController!');
        throw $e;
    }

    return $user->id;
}

Thanks for your help.

node, unit-testing and mocking with sinon

So I am using a test suite of Chai, rewire, sinon, and sinon-chai to test some node javascript. This is my first time trying to set this up so I could use some pointers. The function I am trying to test looks like so :

UserRoles.get = function(ccUrl, namespace, environment, ccToken, authPath) {
    var crowdControl = new CrowdControl(ccUrl, namespace, environment, ccToken, authPath);
    return q.Promise(function(resolve, reject) {
        crowdControl.get().then(resolve).fail(reject).done();
    });
};

Inside a document that exports as UserRoles. So I have the initial set up working fine, where I am having troubles is mocking to test this function. I'm trying to mock the new CrowdContol part so my attempt to do that looks like so : http://ift.tt/1J8CC8v .

so I'm trying out the

testHelpers.sinon.stub(CrowdControl, "UserRoles");

to intercept and stub

var CrowdControl = require('./crowdcontrol');

then just running

userRoles.get;

console.log(CrowdControl);

And it seems the stub is not being called ( it logs it's a stub but not that it has been called). I will also need to stub the crowdControl.get() hopefully too, however I was trying to get this simple part working first. Not sure what I need to be doing differently to get this to work here. This is my first time unit testing in node, I've done a bunch in angular where I could just "mock" the CrowdControl, but I'm not sure how it works in node.

continue test after assertion fail using xmlrunner and unittest in python

I am writing a simple test using XMLrunner and unittest in python. When using assert the test fails and does not continue. I want the test to continue to the end and then fail. Is it possible? I will attach a very simple code demostrating what I need to do.

import xmlrunner
import unittest

class TestExp(unittest.TestCase):

    def setUp(self):
        self.list = range(1,10)

    def test_example(self):
        for i in self.list:
            self.assertTrue(i == 3, str(i) + "message")


if __name__ == '__main__':
    unittest.main(
        testRunner=xmlrunner.XMLTestRunner(output='test-reports'),
        failfast=False, buffer=False, catchbreak=False)

as an output an XML is generated, however containing only the first failed assertion, I need to run the rest of the assertions and also generate test-reports from them, when using try/except i cannot see the testcase fail in XML file.

<?xml version="1.0" ?>
<testsuite errors="1" failures="0" name="TestExp-20150429152621" tests="1" time="0.000">
    <testcase classname="TestExp" name="test_example" time="0.000">
        <error message="1message" type="AssertionError">
<![CDATA[Traceback (most recent call last):
  File "xmlrunsample.py", line 14, in test_example
    self.assertTrue(i == 3, str(i) + "message")
AssertionError: 1message
]]>     </error>
    </testcase>
    <system-out>
<![CDATA[]]>    </system-out>
    <system-err>
<![CDATA[]]>    </system-err>
</testsuite>

This is what i get as test-report output, containing only 1 assertion fail, how can i make the script continue to assert the rest of test cases?

Is it possible to debug a JavaScript QUnit test?

Is it possible to set a breakpoint in a JavaScript QUnit test and run it in a browser's debugger somehow?

I have tried solution described here, but I just want to avoid the way when you have to create HTML page with all the links and so on.

I am using VS 2012 and runnings tests from it.

Unit Testing in Python for fileinput and commands.getstatusoutput

def find_repalce():
    name_file = '/tmp/name.txt'
    text_to_search = "find"
    text_to_replace = "replace"
    new_name_file = '/tmp/new_name.text'

    if os.path.isfile(name_file):

        move_ping_file = commands.getstatusoutput("sudo cp " + name_file + " " + new_name_file)

        if not move_ping_file[0]:
            return 0

        os.system("sudo chmod 666 " + new_name_file)

        for line in fileinput.input(new_name_file, inplace=True):
            sys.stdout.write(line.replace(text_to_search, text_to_replace))

        os.system("sudo chmod 644 " + new_name_file)

        replace_file = commands.getstatusoutput("sudo cp " + new_name_file + " " + name_file)

        if not replace_file[0]:
            return 0
        return 1

    else:
        return 0 

Hi I am new to unit testing in python. I have tried mocking but it is no use? Can anyone help me mock the file and handle the default calls in the python?

Any Suggesstion kindly comment it below

Thanks in Advance

Create a mock calling a constructor

Suppose I have the following class:

class Person {
  private String name;
  private Integer id;
  public Person(String name){
     this.name=name;
     this.id=random();
  }

  int random() {
     return new Random().nextInt();
  }
}

It's possible to create a partial mock for a Person class by calling the constructor with mocked random() method? I mean something like this:

Person a=EasyMock.createMockBuilder(Person.class)
                  .withConstructor(String.class)
                  .withArgs("Albina")
                  .addMockedMethod("random")
                  .createMock();

Unit testing using Eclipse - JUNIT

I wrote an android application that uses GPS mainly, using Eclipse.

I want to do a JUNIT test for the application.

I have searched the internet but I still don't understand. please help me.

How do I test my methods, such as saving coordinates or finding coordinates...etc.

My main activity has only one click button that takes the user to location services page... how is that all tested?

UnitTest failing only when all tests get executed at once

I'm currently facing an odd problem when running a Microsoft C++ UnitTest within VS2013.

The test is failing each time I execute Run All tests in the IDE, but when I use Run Selected Tests on the specific one, it succeeds.

What I'm testing for is the usage of my own BinarySearchTree class. In case of failure, the exception code C0000005 gets returned (this may be due to wrong internal linkage of pointers).

So what can be the reason for this?

How to unit test angularjs route's resolve with karma and mocha+chai?

I am working on an app where I need to resolve promises in the router (ngRoute). The problem is that I am not sure how to write the unit tests for this, I am using karma with mocha and chai.

Here is the part of the code I'd like to test:

function config ($routeProvider) {
    $routeProvider
        .when('/', {
             templateUrl: 'views/orders.html',
             controller: 'OrderController',
             controllerAs: 'vmr',
             resolve: OrderController.resolve,
             data: {...}
    });
}

function OrderController (OrderService, newOrders) {
    this.newOrders = newOrders;
}

OrderController.resolve = {
    newOrders: function (OrderService) {
        return OrderService.getOrders();
    }
};

This is how I started to write my unit tests when I didn't have the resolve part yet:

describe('OrderController', function() {

    'use strict';

    var controller,
        service,
        httpBackend;

    beforeEach(module('myApp.orders'));

    beforeEach(inject(function($controller, _OrderService_, $httpBackend) {
        service = _OrderService_;
        httpBackend = $httpBackend;
        // Create the controller
        controller = $controller('OrderController', {});
    }));

    beforeEach(function() {
        httpBackend.when('GET', 'url/to/get/orders')
            .respond(200, {[...]});
    });

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

    it('should get the list of new orders', function() {
        httpBackend.flush();
        console.log(route);
        expect(controller.neworders).not.to.undefined;
        expect(controller.neworders.length).to.equal(3);
    });
});

At this point is where I am getting the error:

Unknown provider: newOrdersProvider <- newOrders

I understand why I get this error, but I don't know how to solve it. Basically I don't know how to test the promise that resolves in the route.

Thanks in advance for your help!

How to reuse the same tests to test different implementations?

My language is python 3 and I am trying to understand how to use the same set of tests to test different implementations of the same algorithm.

So far I am looking at the built-in unittest and my impression is that I have to make some sort of a class hierachy: a class that inherits from unittest.TestCase and implements all the actual tests and several descendants from its class that each test particular implementations with the tests from the parent.

However, this is just my idea of how it should look like. Could you please tell me how to actually use the same set of tests to test different functions that implement the same algorithm?

Stubbing with proxyquire

How would I stub the following module with proxyquire and sinon:

var email = require("emailjs").server.connect.send();

I did the following, but its not working, because when I try to trigger an error within send() it still sends the email.

sendMailStub = sinon.stub(email, "send");    
testedModule = proxyquire('../index.js', {
                'email': {
                    'server': {
                        'send': sendMailStub
                        }
                    }
            });

And also tried:

testedModule = proxyquire('../index.js', {
            email: {send: sendMailStub}
        });

Resolving relative path in when running ClasspathSuite

When I run JUnit tests using ClasspathSuite and one of the unit tests wants to load a file using a relative path, it will use the base path of ClasspathSuite instead of the base path of the unit test.

So for example if the unit test tries to load a file like this:

File file = new File("src/test/resources/test.xml");

it will try to load that file relative to the location of ClasspathSuite and not relative to the location of the unit test.

Is there any way to change this?

Error: Unexpected request: POST Karma-jasmine-angular

the actual scenario is like when I am trying to test my angular js controller and service together in which first I call a get ajax request and on its success I call a user service which also contains a post ajax request. When I run test I got the following error.

Error: Unexpected request: POST http://localhost:8080/services/access No more request expected in /home/test/WebstormProjects/test2/bower_components/angular-mocks/angular-mocks.js

I found some similar questions in stack overflow but it is not fit my scenario. These are the following questions which I found.

Unexpected request: GET No more request expected at $httpBackend

Mocking $httpBackend - how to handle "Unexpected request, No more request expected"?

AngularJS $httpBackend - "No more request expected" error

Here is my code which I did and try.

test.js

describe('Login controller',function(){

  beforeEach(module('app'));

  var httpBackend,ctrl, scope,userService;

  beforeEach(inject(function($controller, $rootScope,$httpBackend,$injector,_userService_) {

    scope = $rootScope.$new();
    httpBackend = $injector.get('$httpBackend');

    userService = _userService_;

    ctrl = $controller('LoginController', {
      $scope: scope
    });
  }));

  it('should set authentication true', function() {

    scope.authenticateUser();

    var username = 'test';
    var password = '123456';
    var requestToken = "";

    httpBackend.whenGET('http://localhost:8080/services/request').respond(200,{
      status : 0
    });

    httpBackend.expect('POST', 'http://localhost:8080/services/access').respond(200, {
      status:"success"
    });

    var returnedPromise = userService.authenticateUser(username,password,requestToken);

    httpBackend.flush();

    expect(scope.result).toEqual(0);

    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();

  });
});

app.js

app.controller('LoginController', function LoginController($scope,$http,userService) {
  $scope.test="hello";
  $scope.authenticateUser = function(){
    var username = 'test';
    var password = '123456';
    var token = "";

    $http.get('http://localhost:8080/services/request').success(function(data) {
        $scope.result = data.status;
        userService.authenticateUser(username, password, "").then(function(response){});
    });
  };
});

userService.js

userService.authenticateUser = function(username, password,requestToken){

            var status = $http({
                method: 'POST',
                url: "http://localhost:8080/services/access",
                data: $.param({username:username,password:password,request_token:requestToken}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}

            }).success(function(data, status, headers, config) {
                return data;

            }).
              error(function(data, status, headers, config) {
                return null;
            });
            return status;
        };

        return userService;

I am new with karma-jasmine-angular test and I am struggling with this kind of scenarios. Please provide me proper guidance to resolve this kind of testing situation. Any help will be appreciate. If possible please suggest me some good demos to test a service which called on success of a service. Thanks in advance.

mardi 28 avril 2015

Unit testing Ember utils. TypeError: factory.create is not a function

I've created util here: app/utils/filters-serialization.js

export default function filtersToString(search) {
  return 'keyword$MO';
};

And test here: tests/unit/utils/filters-serialization-test.js

import {
  moduleFor,
  test
  } from 'ember-qunit';

moduleFor('util:filters-serialization', {
});

test('it exists', function(assert) {
  var service = this.subject();
  assert.ok(1);
});

I run tests and I've got an error TypeError: factory.create is not a function The problem occurs when I call this.subject();. If I remove this line everything works well. But I It will be great if someone could share his experience in writing unit tests for ember utils. I found another question: Unit testing modules in app/utils for an ember-cli app however this.subject isn't undefined anymore so I think it's good to ask this question again

configuration error PKG_CHECK_MODULES(CHECK,check>=0.9.6) for check framework in ubuntu

I install check-0.9.9 UI(unit testing) framework and trying to configure and execute example test case which is given with check setup but while configuring I am getting this issue. PKG_CHECK_MODULES(CHECK,check>=0.9.6)

I also followed README provided by this example.you can find this example source in following path check0.9.9/doc/examples.

How to use mocking in this case?

Here is my problem:

This is the method for which i am trying to write test case.

This method trying to create instance of "HttpClient" but this server is not available on my side.

So i am trying to achieve this by using mocking, But i am not successful in that.

So could anyone tell me that how to do that?

Here is the method:

  public boolean callGet(final boolean keepResult) {
            boolean ok = false;
            if (url != null) {
                try {
                    log.appendLine("Url:");
                    log.append(url);
                    final HttpClient client = new HttpClient();
                    setAuthentication(client);
                    final GetMethod method = new GetMethod(url);
                    if (Utils.isFilled(userAgent)) {
                        method.setRequestHeader("User-Agent", userAgent);

                    }
                    status = client.executeMethod(method);
                    ok = (status == HttpStatus.SC_OK);
                    log.appendLine("Status http call:");
                    log.append(status);
                    if (ok) {
                        if (keepResult) {
                            if (maxSizeResult > 0) {
                                result = method
                                        .getResponseBodyAsString(maxSizeResult);

                            } else {
                                result = method.getResponseBodyAsString();

                            }
                        }
                    }
                } catch (final Exception e) {
                }
            }
            return ok;

This is my unit test method:

   @Before
        public void start() {
            urlcaller = new UrlCaller();
            UrlCaller mock1 = Mockito.mock(UrlCaller.class);
            Mockito.when(mock1.callGet(true)).thenReturn(true);

        }

        @Test
        public void testSetUserAgent() throws HttpException, IOException {

        boolean t1 = urlcaller.callGet(true);

        System.out.println(t1);

    }

}

This is the error i am getting :

Problem:
    UrlCaller.java
    javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
        ...
        at de.bcode.utilsWithLog.UrlCaller.callGet(UrlCaller.java:115)
        at de.bcode.utilsWithLog.TestUrlCaller.testSetUserAgent(TestUrlCaller.java:52)
    Caused by:
        java.io.EOFException: SSL peer shut down incorrectly
            at sun.security.ssl.InputRecord.read(InputRecord.java:482)
            ...
            at de.bcode.utilsWithLog.UrlCaller.callGet(UrlCaller.java:115)
            at de.bcode.utilsWithLog.TestUrlCaller.testSetUserAgent(TestUrlCaller.java:52)
false

Thank you for reading all the question :-) Hope it is clear enough.

how to write a Unit Testing for Microsoft Azure worker roles project?

I have created the Microsoft azure worker role for background work process. In this worker role we have write some code related to background process it will connect to database and get the data do some logic.

So i want to write Unit testing for this whole project. and i also new to Unit testing.

Please give me some idea or links to write my first unit testing.