jeudi 31 décembre 2015

Parameterize Spock setup

Is it possible to parameterize a Spock setup?

By that I mean, imagine I have an object whose state I want to test. The object can have multiple states, but to simplify things, let's say there's one I'm particularly interested in, S1.

There are multiple ways to get the object to S1. I'm testing state, so all the tests for S1 will be the same regardless of how the object reached S1. The one thing that would differ between test cases would be the setup strategy.

One way to deal with this is to have a base test case (or "spec" to use Spock parlance) and subclasses that only supply different setup strategies.

But, given the nice data-driven features of tests that Spock offers, I got to wondering if there might be some way to parameterize the setup in such a way that I wouldn't need concrete subclass specs.

In effect, I would be saying, here's a spec, now run it with these different ways of executing setup.

C# If Assertion Fails Run Function

I currently have a test suite using Nunit and C# with Selenium WebDriver using assertions, is there a way to have a function run only if the assertion fails. Normally this will continue to the teardown and then proceed to the next test, however I need to reset certain parameters on the test if the previous test fails. What is the best way to do this?

QUnit doesn't rerun all failed tests

I'm using QUnit for the first time and I've run into a weird problem that makes me think I've missed some fundamental part of the setup. I have four tests set up to all fail. When I first load the page, QUnit correctly reports all four failures. When I reload the page, only two tests appear to be run (and they fail).

I've found that if I remove the key-value pairs in the Session Storage, all four tests will be run again. But from my reading of the QUnit docs, it seems like it should be rerunning all of them. "Whenever a test fails, QUnit stores the name of that test in sessionStorage. The next time you run a testsuite, that failing test will run before all other tests" (from http://ift.tt/1R0Wa6b). If I fix the two tests that are reported to be failing, then QUnit will pick one of the others to rerun.

How can I make it run all failed tests every time the page is reloaded?

Thanks!

Here's my code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>QUnit Example</title>
    <link rel="stylesheet" href="qunit-1.20.0.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="qunit-1.20.0.js"></script>
<script type="application/javascript">

    QUnit.test( "input0", function(assert) {
        assert.equal("qunit", "qunit1", "qunit works");
    });
    QUnit.test( "input1", function(assert) {
        assert.equal("qunit", "qunit2", "qunit works");
    });
    QUnit.test( "input2", function(assert) {
        assert.equal("qunit", "qunit3", "qunit works");
    });
    QUnit.test( "input3", function(assert) {
        assert.equal("qunit", "qunit4", "qunit works");
    });

</script>
</body>
</html>

The `AllInstances` using in the `MS Fakes`

MS Visual Studio 2015 Enterprise.

From MSDN:

To use a shim for an instance method, write AllInstances between the type name and the method name:

System.IO.Fakes.ShimFile.AllInstances.ReadToEnd = ...

But when I write . after ShimFile the IntelliSense has not AllInstances item in the combobox:

enter image description here

Also I try to do the same for DateTime and I see other problem: the AllInstances is exists, but the IntelliSense has not items for it:

enter image description here

Why does it happen?

Jenkins not failing on tests that fail in coverage

I have Jenkins setup to run tests before anything gets pushed into our QA environment. Recently I added python coverage to check code coverage of the tests.

Issue I have is not I see in the output that tests are failing, but the build still pushes through.

I am running the following in a bash script:

coverage run manage.py test --settings=my.settings.jenkins --noinput

When I was running the tests normally without coverage, if the test failed, the build would fail, this is no longer the case.

The project is a Django project on Python 3, any help would greatly be appreciated.

Use mock to patch sleep in unit test

I have a piece of code sitting in a module like this:

MyWorker.py:

from gevent import sleep

class MyWorker(object):
  def run(self):
    for _ in range(10):
      do_something()
      sleep(1)

Then I want to test this while mocking sleep. I tried multiple ways of doing it but all failed. One way I thought should be working:

from mock import patch
from x.y.z.MyWorker import MyWorker

class TestWorker(unitest.testCase):
  def Test_my_worker(self):
    with patch('x.y.z.MyWorker.sleep'):
      a = MyWorker()
      a.run()

How to implement ShowDialog mock method for unit test for vsPackage(VS 2013)

I am writing a vsPackage for VS 2013 and need to show a modal dialog window. I need to write a unit test, but ShowDialog method is not defined in any of IVsUIShell interfaces. Any suggestion is appreciated.

writing a unit test for an angular directive that requires ng-model

I am new to unit testing and trying to figure out how to set it all up. I have the following directive:

(function () {
    'use strict';

    angular
        .module('hntb-utils')
        .directive('notZero', notZero);

    //notZero.$inject = [];

    function notZero() {
        return {
            require: 'ngModel',
            link: link,
            restrict: 'A',
            scope: '='
        };

        function link(scope, element, attributes, ngModelCtrl) {
            ngModelCtrl.$validators.notZero = function (value) {
                return value != 0;
            }
        }
    }

})();

This directive (if added as an attribute not-zero to an element that also uses ng-model) ensures that the model value is not zero by adding a validator to the ngModelController.

I am trying to figure out how to test this directive. I figure I should probably have something like:

it("should ensure model is not zero", function () {
...
});

I am just really stuck on the implementation. I know I should use angular-mocks but how? What do I mock up?

Thanks in advance.

Local Variable Unit Testing

I am coding in C++, and am unit testing a function. This function has a set back though, as I am testing it from an outside source file using GoogleTest. I can't think of way of testing a certain local variable inside it. The function creates a class pointer variable inside itself and deletes it at the end of the function. If I move the local variable declaration into the .h for the overall class, it works just fine and I can do what ever I want to the local variable regardless of it being deleted in the end. So My question is, given that I am not allowed to alter the original setup, is there a way that anyone knows of to access the info from a local variable via some tricky logic or programming voodoo you guys know of? Any advice is appreciated! Also the pointer object in question points to methods in its class and does data manips via input. Ex: pointerA->setWidth(int, int); I need to get to this pointerA in general.

foo(int number, int num) {
   classA* pointerA = new classA;  
   pointerA->setWidth(number, num);  
   //other data manipulations  
   delete pointerA;
}

Example of Test:

EXPECT_EQ(pointerA->setWidth(returns width), 2); //checks to see if it returns correct value of 2

Also the reason I want to be able to do it without having to alter any code is because I'm hoping to let it be automated and run the test every time the code is compiled. It's how I have it set up for all my other tests, but they don't have local vars.

How to use ngMock to inject $controller

I'm trying to learn unit testing for Angular using Karma, Jasmine, and ngMock. There are at least 2 places in the Angular docs that show how to write unit tests for a controller, and I just have a couple of questions about how they're doing things.

From the Controller docs, section on testing controllers:

describe('myController function', function() {

  describe('myController', function() {
    var $scope;

    beforeEach(module('myApp'));

    beforeEach(inject(function($rootScope, $controller) {
      $scope = $rootScope.$new();
      $controller('MyController', {$scope: $scope});
    }));

    it("...");
  });
});

Question 1: This one mostly makes sense to me, but here's something I don't quite get. I understand that $controller is grabbing an instance of "MyController", but it looks like what is returned isn't being saved or used anywhere, so the only thing I can think of is that we grab that controller in order to get the correct $scope object? Even that seems like it isn't being saved in a variable anywhere, so I'm still a little confused on how this works behind the scenes. I had the same confusion about how module() works because we seem to be declaring which module we're using, but not saving or using it anywhere else. Is there something behind the scenes that caches the module/controller/scope so we don't have to save it manually or something?


Here's another example from the Unit Testing docs:

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');
    });
  });
});

Question 2: Here in the beforeEach function it's doing the underscore wrapping thing. Is that just so that you can keep the same service name throughout without having to change it?

Question 3: The it() block then uses $controller to do its thing, this time saving what gets returned to var controller but seemingly still never using it beyond this point. So why save it to a variable? The only thing I can think of offhand is that you save it in case you need to use it again inside this it() block, but they just didn't in this example?


I've been looking all over for a good explanation and I can't seem to find one. Sorry if there's a silly explanation I'm missing, but I'm on a time crunch and can't spend any more time spinning my wheels.

Swift Unit test- How do I assert that a CGColor is what it's supposed to be?

Using Xcode V7.2. Trying to unit test, need to verify that the correct color has been set, and get this message:

Cannot invoke 'XCTAssertEqual' with an argument list of type '(CGColor, CGColor)'

How do I assert that a CGColor is what it's supposed to be?

Mock System.Net.FtpClient GetHash method

Is it possible to mock public FtpHash GetHash(string path) of class System.Net.FtpClient.IFtpClient

The problem is that FtpHash has an internal constructor. Is there a way to mock it?

Android - How can I mock a lack of camera when testing my app?

I would like to check that my app shows an error message when the device it is running on has no camera. I have tried passing in a mock context but mockito gives an error when I try to mock the CameraManager class as it is declared final. Surely android has a simple solution for this? Here's my attempt:

public class CreateNewIdentityActivityUnitTest extends ActivityUnitTestCase<CreateNewIdentityActivity> {
    public CreateNewIdentityActivityUnitTest() {
        super(CreateNewIdentityActivity.class);
    }

    public void testErrorMessageDisplayedWhenNoCamerasExist() throws Exception {
        // Create the mock cameramanager
        // THIS LINE FAILS BECAUSE CAMERAMANAGER IS FINAL
        CameraManager mockCameraManager = mock(CameraManager.class);
        String[] cameraIdList = {};
        when(mockCameraManager.getCameraIdList()).thenReturn(cameraIdList);

        // Create the mock context
        Context mockContext = mock(Context.class);
        when(mockContext.getSystemService(Context.CAMERA_SERVICE)).thenReturn(mockCameraManager);

        // Start the activity
        Intent intent = new Intent(mockContext, CreateNewIdentityActivity.class);
        Activity activity = startActivity(intent, null, null);

        // Verify that the error message was made visible
        TextView errorTextView = (TextView)activity.findViewById(R.id.ErrorTextView);
        assertNotNull(errorTextView);
        assertEquals(View.VISIBLE, errorTextView.getVisibility());
    }
}

Urls with name are not accessible in Django Client Tests (NoReverseMatch error)

I am writing tests for my views in django app. Previously they were in same directory in which my views are. They were working fine. But then I moved them in folder name 'tests' in django app. There are no import errors but I am getting 'NoReverseMatch' error. My directory structure is as follow.

Project
    settings.py
    |my_app
        |tests
            |tests.py
            |__init__.py
        |migrations
           |__init__.py
        |views.py
        |models.py
        |urls.py

My code is as follow

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django
django.setup()
from rest_framework.reverse import reverse
from rest_framework import status
from rest_framework.test import APITestCase

class MyTests(APITestCase):

def test_01(self):
    url = reverse('login')
    data = {'username': 'username', 'password': 'StrongPassword'}
    response = self.client.post(url, data)
    self.assertEqual(response.data, my_expected_output)

The error which I am getting is

NoReverseMatch: Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

Can anyone tell me where I am doing something wrong

Angular unit-test - mocking method in controller

I need to mock the method of service in the controller. I know how to mock simple service like service.method, but not like this one. I dont know how to mock "action.user.update". If i tried to spy on it, i received an error 'Cannot read property 'update' of undefined'.

JsFidleDemo

My service:

.service('action', ['$http', '$q', function ($http, $q) {
    var service = {};

     service.user = {
        update: function (data, config) {
             return service.run({
                name: config.name,
                call: $http({
                    method: "POST",
                    url: "/user/edit",
                    data: data
                }),
                success: config.success,
                error: config.error
            });
        }
    };

    return service;
}]);

Insert a file into specific directory/node using vfsStream

The use case of vfsStream is as follows:

$directories = explode('/', 'path/to/some/dir');

$structure = [];
$reference =& $structure;

foreach ($directories as $directory) {
    $reference[$directory] = [];
    $reference =& $reference[$directory];
}

vfsStream::setup();
$root = vfsStream::create($structure);
$file = vfsStream::newFile('file')
    ->at($root) //should changes be introduced here?
    ->setContent($content = 'Some content here');

The output of vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure() is

Array
(
    [root] => Array
    (
        [path] => Array
        (
            [to] => Array
            (
                [some] => Array
                (
                    [dir] => Array
                    (
                    )
                )
            )
        )

        [file] => Some content here
    )
)

Is it possible to insert a file into specific directory, for example, under dir directory?

Mock/Stub a RuntimeException in unit test

In School class, I have a start() function which invokes another function doTask():

pubic class School {
    public void start() {
       try {
         doTask();
       } catch(RuntimeException e) {
          handleException();
       }
    }
    private void doTask() {
      //Code which might throw RuntimeException
    }
}

I want to unit test start() with RuntimeException:

@Test
public void testStartWithException() {
  // How can I mock/stub mySchool.start() to throw RuntimeException?
  mySchool.start();
}

It is not easy for my implementation code to throw the RuntimeException, how can I make the test code to mock a RuntimeException & throw it?

(Besides pure JUnit, I am considering using Mockito, but not sure how to throw RuntimeException)

Spring MVC Junit Test DB auto increament

DB table is

CREATE TABLE `test` (
  `b_index` int(10) NOT NULL AUTO_INCREMENT,
  `password` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`b_index`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

and insert board mybatis mapper is

<insert id="insertBoard" parameterType="hashmap">
    <![CDATA[
        INSERT INTO board
        (
            password
        )
        VALUES
        (
            #{password}
        )
    ]]>
</insert>

Junit Test Class is

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/application-context.xml")
public class BoardServiceTest {
    @Autowired
    private BoardService boardService;

    private static final String TEST_PASSWORD = "test";

    private Board board = null; // test vo object

    @Before
    @Transactional
    @Rollback
    public void setup() throws Exception {
        Board board = null; // test vo object

        board = new HistoryBoard();
        board.setPassword("TEST");

        this.board = board;

        boardService.insertBoard(board);
    }
}

the problem is when i insertBoard in Junit Test Class 'BoardServiceTest'

always b_index set '0'

so when i try like this in BoardServiceTest class

@Test
@Transactional
public void validPassword() {
    String pwd = boardService.selectPassword(board);

    assertEquals(TEST_PASSWORD, pwd);
}

this test always FALSE becuase board object index is '0'

but actually b_index is not '0' because AUTO_INCREMENT is not '0'

@Test
@Transactional
public void getAllBoard() {
    List<Board> selectAllBoardList = boardService.selectAllBoardList();

    System.out.println("TEST : " + selectAllBoardList.get(0).getB_index());

    assertEquals(false, selectAllBoardList.isEmpty());
}

when this this TEST log TEST : 10

how to test DB in JUnit like this case?

Always need to set AUTO_INCREMENT=0 when i try JUnit test?

Unit testing on an Angular app with Karma

So i'm quite new with test cases and I have a small questions (specific to my case).

I am currently developing an Angular app and started to do unit test with Karma (Mocha/Chai). The back end of this app is a node RESTful API. So basically, the app is a bunch of controllers and services making some basic CRUD operations.

On creation of a new user for example, I handle the verification in the html form using angular's form directives. In the server side, there is also a verification on the object received. So generally my functions on controllers are no more then things like:

create() {
  UserService.create(vm.newUser).then(callBackToDisplaySuccessOrErrorMessage); 
}

It will probably sounds silly, but i'm new in this domain (test cases) and i am a little bit confused, so my first question is:

since the http calls are mocked, what is the point to do unit testing in app such as mine ?

And my second question is :

how to unit test basic app like in my case in a proper way ?

How to test stores/actions?

I need to test the alt store; for which I have raised an action using alt dispatcher and trying to listen it at the action listener. But I got my alt object as undefined. Any idea plzz..

Action Class:

var alt = require('../alt');
var LocationSource = require('../sources/LocationSource');

class LocationActions {
updateLocations(locations) {
 this.dispatch(locations);
}

fetchLocations() {
this.dispatch();
var actionDispatcher = this;

LocationSource.fetchLocations().then(function(items) {

actionDispatcher.actions.updateLocations(items);

});
}

locationsFailed(errorMessage) {
this.dispatch(errorMessage);
}

favoriteLocation(location) {
this.dispatch(location);
}

fetchedLocation(location) {
this.dispatch(location);
}

fetchLocation(locationId) {

var actionDispatcher = this;

actionDispatcher.dispatch();

LocationSource.fetchLocation(locationId).then(function(item) {

actionDispatcher.actions.fetchedLocation(item);

});
}
}

module.exports = alt.createActions(LocationActions);

My Store:

var alt = require('../alt');
var LocationActions = require('../actions/LocationActions');

class FavoritesStore {
constructor() {
this.locations = [];

this.bindListeners({
  addFavoriteLocation: LocationActions.FAVORITE_LOCATION
});
}

addFavoriteLocation(location) {
this.locations.push(location); 
}

onRemoveFavoriteLocation(){

}

}

module.exports = alt.createStore(FavoritesStore, 'FavoritesStore');

MY Alt js:

var Alt = require('alt');
var alt = new Alt();
var chromeDebug = require('alt/utils/chromeDebug')

chromeDebug(alt);

module.exports = alt;

Heres the test file:

"use strict";
jest.dontMock('../src/js/stores/FavoritesStore');
jest.dontMock('../src/js/actions/LocationActions');
jest.dontMock('../src/js/alt');
import alt from '../src/js/alt';
var fav =require('../src/js/stores/FavoritesStore');

import LocationActions from '../src/js/actions/LocationActions';

describe('fav', function() {

 beforeEach(function() {
sinon.spy(alt.dispatcher, 'dispatch');

alt.dispatch(LocationActions.FAVORITE_LOCATION, {id:15, name:'khi'});
});

afterEach(function() {
// clean up our sinon spy so we do not affect other tests
alt.dispatch.restore();

});
it('add a location to favorites list ', function() {

  var id: 15, name: 'San Francisco' ,
  action = LocationActions.FAVORITE_LOCATION;
    console.log({id:15, name:'khi'});
  // fire the action
  LocationActions.favoriteLocation({id:15, name:'khi'});

});
});

mercredi 30 décembre 2015

How to dynamically change target for unit tests in Xcode 7?

I have a project that has multiple different targets/schemes (~38 of them as of writing this question) and I am trying to get unit testing working properly across all of the different targets. I got things working with one target, and tried adding my testing target to all of the different schemes, but it looks like when tests run for each scheme they actually run on the same, original target.

Looking in the project file I see that there's a specific Host Application associated with my testing target, and in the build settings the Bundle Loader and Test Host point to that same Host Application.

Is there any way to override those values for each scheme to run the tests against the current scheme's build target? Or some other way to set up a single test target to run across multiple build targets?

What is the shortcut for running the unit tests in Xcode 7?

I tried using this combination: "Command + U". But it seems this runs my UI tests.

I checked the Build Settings -> Packaging -> Product Module Name is NameOfProjectUITests.

I am not sure if this needs to be changed to be the NameOfProjectTests. Even so, trying to change it shows a weird name: $(PRODUCT_NAME:c99extidentifier)

Or is there another shortcut to run all tests ?

Can't get JUnit tests to fail in Android Studio

I'm trying out Android development, but haven't come too far because I'm unable to get a test case to fail.

I have the following test case in the androidTest folder:

package com.example.aaronf.myapplication;

import android.test.*;

public class ToDoListTest extends AndroidTestCase {

    private void newToDoListHasNoItems() {
        assertEquals(new ToDoList().length, 0);
    }

    private void addingToDoGivesLengthOfOne() {
        ToDoList toDoList = new ToDoList();
        toDoList.add(new ToDo());
        assertEquals(toDoList.length, 1);
    }

    public void runTests() {
        newToDoListHasNoItems();
        addingToDoGivesLengthOfOne();
    }

    public ToDoListTest() {
        super();
        runTests();
    }
}

The ToDoList class looks like:

package com.example.aaronf.myapplication;

public class ToDoList {
    public int length = 0;

    public void add(ToDo toDo) {

    }
}

It seems like it should fail on addingToDoGivesLengthOfOne(), but I get a green bar.

rails unit testing with ActiveRecord associasions without hitting the DB

TL;DR I'd like to know if I can test model methods that use querying (i.e find, where) without persisting test objects to the database.

So I'm new to rails, and working on an existing codebase.
One thing I've noticed is that our unit tests take forever to run.
Upon investigation, the culprit was, of course, that we persist everything to DB when we test our models.
So, I set out to try and write model tests that don't hit the DB, but I've come across a snag:
When a model has an association with other models, any operations that are performed on it assume that everything is persisted.

Let's take a look at an example-

class Parent < ActiveRecord::Base
  has_many :children, dependent: :destroy

  def default_child
    children.find_by(default: true)
  end

end

So naturally I want to test that my default_child method is working:

parent = Parent.new
default_child = parent.children.build(default: true)

assert_equal default_child, parent.default_child

but this test fails, because the actual result of parent.default_child is nil!
This is because internally, the default_child method uses find_by, which, it seems, only works in the context of persisted objects.

So I'm forced to write the test like so-

parent = Parent.new
# I don't want to do this!!
parent.save
# why 'create' and not 'build'?
default_child = parent.children.create(default: true)

assert_equal default_child, parent.default_child

Which is uglier and slower.
Is there any way I can test these operations in memory?

I've tried setting children manually (parent.children = [ child1, child2 ]).
This does not cause an error, but it seems that find_by doesn't look there, but rather in the DB...

I see that a similar question came up 3 years ago, without a conclusive answer, I'm wondering if anything's changed since then..

P.S. bonus question- what can I do about validations which are on: update? seems like I have to persist the test object at least once before they are invoked..

CakePHP 3: Set current time for unit testing

With CakePHP 3, I'm using the built in class Cake\I18n\Time to calculate the difference in time from an API response and the current time. The results are getting stored for a unit test, but I don't know how to set what the current time is, so the expected results keep changing.

Here's the unit I'm trying to test:

$apiTime = Time::createFromTimestamp($apiTimestamp);

// Get the time the prediction was generated
$currentTime = Time::now();

return (int)(($apiTime->getTimestamp() - $currentTime->getTimestamp()) / 60);

So, is there any way that I can set the current time? That way I would be able to actually know what the expected results are.

I keep on getting DisconnectedContext exception, why?

So, when debugging my code I get a DisconnectedContext exception the moment I try to step into the assignment of a variable (doesn't matter what kind of variable).

In the following example I get the exception the moment it get's to bool l2 while the assignment of bool l doesn't cause the exception.

bool l = driver.Url.Contains("something");
bool l2 = driver.FindElement(By.CssSelector("#Csssomthing")).IsElementVisible();
if (l || l2)
{
    //do something 
}

public static bool IsElementVisible(this IWebElement element)
    {
        return element.Displayed && element.Enabled;
    }

Here's the call stack of the l2 assignment:

bot.dll!bot.botExtensions.LoginToAccount(OpenQA.Selenium.IWebDriver driver, string email, string password) Line 74 C#

bot.dll!bot.TheBot.Test() Line 48 C#

[Native to Managed Transition]

[Managed to Native Transition]

Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethodRunner.DefaultTestMethodInvoke(object[] args) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethodRunner.RunTestMethod() Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethodRunner.ExecuteTest() Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethodRunner.ExecuteInternal() Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethodRunner.Execute() Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.UnitTestRunner.RunInternal(Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestMethod testMethod, bool isDataDriven, System.Collections.Generic.Dictionary runParameters) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.MSTestFramework.UnitTestRunner.RunSingleTest(string name, string fullClassName, bool isAsync, System.Collections.Generic.Dictionary runParameters) Unknown [AppDomain (C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\Extensions\Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll, #2) -> AppDomain (UnitTestAdapter: Running test, #4)]
Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.ExecuteTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.ITestExecutionRecorder testExecutionRecorder, Microsoft.VisualStudio.TestPlatform.MSTestFramework.UnitTestRunner testRunner, Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.TmiTestRun tmiTestRun) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.ExecuteDurontoTestsInternal(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.ITestExecutionRecorder testExecutionRecorder, string source, Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestRunDirectories runDirectories, Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.TmiTestRun tmiTestRun) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.ExecuteDurontoTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle frameworkHandle, string source, Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestRunDirectories runDirectories, Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.TmiTestRun tmiTestRun) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.ExecuteTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestRunDirectories runDirectories, bool isDeploymentDone, string source) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.ExecuteTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestRunDirectories runDirectories, bool isDeploymentDone) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MixedModeExecutor.RunTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle frameworkHandle, Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.TestRunCancellationToken cancellationToken) Unknown Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll!Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.MSTestExecutor.RunTests(System.Collections.Generic.IEnumerable tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle frameworkHandle) Unknown TE.RockSteadyHost.dll!WEX.TestExecution.ExecutionPlugin.ExecuteTests(System.IntPtr context, System.Collections.Generic.IDictionary rockSteadySettings) Unknown TE.RockSteadyHost.dll!WEX.TestExecution.InteropMethods.ExecuteTests(System.IntPtr context, string[] rockSteadySettings, int rockSteadySettingsSize) Unknown [AppDomain Transition]

So any ideas to what I can do?

Is there a way to write a unit test for a target API

I am in the process of writing Android instrumented tests in an area were Robolectric custom shadows fall short.

Ideally, we want to write code that is flexible across all versions of the Android SDK however I am in an edge case situation where I need to write a individual unit test for a method that works only Marshmallow.

I also need to write a unit test that only works for Lollipop and under because of differences in operating system dependencies.

Is there anyway I can do this through Junit4-like annotations or something similar to what Robolectric does where it can ignore running the tests if the SDK is not a good fit?

I do not want to be writing code like this:

// MarshmallowWidgetTest.java
@Test
public void testPrintName()
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        // ...asserts...
    }
}

// LollipopWidgetTest.java
@Test
public void testPrintName()
{
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP)
    {
        // ...asserts...
    }
}

Unit tests for mapping methods that call getters and setters

Suppose I want to create a unit test for a method like this:

public Car map(CarReq request) {

    Car car = new Car();
    car.setPrice(carReq.getPrice());
    car.setColour(carReq.getColour());
    car.setType(carReq.getType());

    // Other 20 lines like these

    return car;
}

I can mock carRequest and tell each method what should return. But that's like not testing anything, as all the method does is getting values from carReq.

I can create a testing carReq object (without mocking) and check that the same values are copied into the output Car object. But that's a lot of work, right?

Isn't there a more intelligent way?

Unit testing angular directive with injected custom services with Karma

I am trying to unit test a directive that has custom services injected into it. With controllers, I am able to do this successfully by creating mock objects and using the following code to instantiate the controller:

controller = $controller('AdminEditDeckCtrl', {$scope: scope, adminService: adminService, $state: state, notificationService: notificationService});

The mock services are injected properly and I can use Jasmine spies to assert that they are being called when they should be.

However, I am not able to instantiate a directive in the same way. I am trying to mock the services using $provide.service or $provide.value, but they don't seem to be being injected properly and Jasmine spies aren't working.

Here is a simplified test spec showing the setup for the test that is failing:

describe("Directive : Search Input", function() {
    var element, e, window, scope, controller, SearchService, userService, $stateParams;

    beforeEach(module("app"));
    beforeEach(module('src/templates/search-input.html'));
    beforeEach(module(function($provide) {
            userService = {
                    profile: {
                            name: 'Unit Test'
                    }
            };
            $stateParams = {
                    query: 'test'
            };
            SearchService = {
                    getSearchSuggestion: function() {
                            var deferred = q.defer();
                            deferred.resolve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
                            return deferred.promise;
                    }
            };
            $provide.service('SearchService', function() {
                    return SearchService
            });
            $provide.value('userService', userService);
            $provide.value('$stateParams', $stateParams);
    }));
    beforeEach(inject(function($compile, $rootScope, _$window_) {
            scope = $rootScope.$new();
            window = _$window_;
            element = angular.element("<search-input></search-input>");
            $compile(element)(scope);
            scope.$digest();
            controller = element.controller("searchInput");
    }));

    it("getSearchChanges should call SearchService", function() {
            spyOn(SearchService, 'getSearchSuggestion').and.callThrough();
            element.scope().getSearchChanges();
            scope.$digest();
            expect(SearchService.getSearchSuggestion).toHaveBeenCalled();
    });
 });

The test is erroring with Expected spy getSearchSuggestion to have been called and it doesn't look like the mock SearchService is being called in the code (or at least the promise isn't returning that array of numbers)

Directive code can be seen here: http://ift.tt/1NQVKeG

Full test spec here:

http://ift.tt/1RRlyeC

Unit Testing Mvc6 TagHelpers

I created several custom Mvc6 TagHelpers and I would like to test their outputs other than on the app.

I've been trying to set up a Unit Test but I'm unable to mock the TagHelperContext.

[Fact]
public void TextboxTagHelperTest()
{
    var t = new TextboxTagHelper();
    var m = new Model1();
    var attr = new TagHelperAttributeList();
    attr.Add(new TagHelperAttribute("asp-for", m.MyProperty));
    var thc = new TagHelperContext(attr, new Dictionary<object, object>(), "");
    var o = new TagHelperOutput("united-textbox", attr, null);

    t.Process(thc, o);

    Debug.Write(o);
}

As anyone set up a Unit Test for Mvc6 TagHelpers?

How to inject mock datasource when using in Junit test

In my application,we bind the datasource through the JNDIlook up using below code:

<bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:/jboss/datasources/efmDS</value>
    </property>
</bean>

Dao has code like below:

   @Autowired
    @Qualifier("jndiDataSource")
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

Now I am having problem while running Junit test case. I am testing a service method which is annotated with @Transactional. This service method internally calls some dao method which I have already mocked using mockito but I am facing issues as when transaction is getting started it tries to fetch connection from datasource which is not present and throws communicationslinkfailure exception How can I mock datasource in this case ? or any other alternative to solve the issue is also appreciated ?

Mock and verify 2 methods public static void and public static boolean from same class using PowerMockito

I have a class say ClassA which has to 3-4 public static methods out of which my requirement is to mock 2 methods one is public static void and other is public static boolean.

Code snippet below

class ClassA{
   public static boolean isConnected(){
     //....
   }
   public static void doSomething(){
    //....
   }
  public static void doSomethingMore(){
    //....
   }
}

Now I have another class say ClassB has method1() calling ClassA.isConnected() and ClassA.doSomething() as below

class ClassB{
   public void method1(){
      if(ClassA.isConnected()){
        //...
      }else{
        ClassA.doSomething()
      }
   }
}

Now I want to do unit testing for method1(), so I'm trying to mock isConnected() and doSomething() using PowerMockito, as below

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassA.class})
public class ClassBTest{ 

@Test
public void testMethod1{
     //variables
     ClassB classB = new ClassB();
    //mock static non-void method
    PowerMockito.mockStatic(ClassA.class);
    PowerMockito.when(ClassA.isConnected()).thenReturn(false);
    //mock static void method
    PowerMockito.spy(ClassA.class);
    PowerMockito.doNothing().when(ClassA.class);
    ClassA.doSomething();
    //execute
    classB.method1();

    //verify static non-void method called
    PowerMockito.verifyStatic(times(2)); 
    ClassA.isConnected();
    //Verify static void method called
    PowerMockito.verifyStatic(times(1)); 
    **ClassA.doSomething();**//getting error at this line
 }
}

ERROR:

Wanted but not invoked com.example.utils.common.ClassA.doSomething(
    );

However, there were other interactions with this mockcom.example.utils.common.ClassA.isConnected();

com.example.utils.common.ClassA.doSomethingMore(
    );

.
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124)
    at org.powermock.core.MockGateway.methodCall(MockGateway.java:63)
    at com.example.utils.common.ClassA.doSomething(ClassA.java)
    at com.example.utils.common.ClassBTest.testMethod1(ClassBTest.java:177)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Grails Unit Test with Filter does not return content

So i have this filter

package filter.api

import grails.converters.JSON

class ApiFilters {

    def apiService

    def filters = {
        apiSafetyCheck(namespace: "api", controller: "customer|status", action: "*") {
        before = {
            if(!apiService?.checkIncludedApiKey(params)) { //Simply returns true if the apiKey was found in the database!
                def returnMap = [
                    "error": "API key was not found",
                    "statusCode": 401 //Just for testing!
                ]
                if(params.outputFormat && params.outputFormat ?.equals("xml")) {
                    def textToRender = apiService?.createXmlFromMapInstance(returnMap)
                    owner?.render(status: 401, contentType: "text/xml", text: textToRender)
                } else owner?.render(status: 401, contentType: "application/json", text: (returnMap as JSON))
                return false //We don't want the action to be processed!
            }
        }
    }
}

My Unit Test looks like this:

package api

import grails.test.mixin.Mock
import grails.test.mixin.support.GrailsUnitTestMixin
import grails.test.mixin.TestMixin
import grails.test.mixin.TestFor
import groovy.json.JsonSlurper
import groovy.util.XmlSlurper
import java.io.ByteArrayInputStream
import java.io.InputStream
import org.xml.sax.InputSource
import static javax.servlet.http.HttpServletResponse.*
import spock.lang.Specification

@TestMixin([GrailsUnitTestMixin])
@TestFor(BearbeitungController)
@Mock(filter.api.ApiFilters)
class ApiZugriffSpec extends Specification {

    void "Test API wihtout Api Key JSON"() {
        when:
            withFilters(action: "customer") {
                controller.someAction()
            }
        then:
            println "Response from Server " + response.text?.toString()
            println "Test 1 " + response?.getRedirectUrl()
            println "Test 2 " + response?.getRedirectedUrl()
            println "Test 3 " + response?.text
            println "Test 4 " + response.contentType
            def obj = new JsonSlurper().parseText(response.text?.toString())
            println "obj?.statusCode " + obj?.statusCode
            response.contentType == "application/json;charset=UTF-8"
            obj?.statusCode?.toString() == SC_UNAUTHORIZED.toString()
    }

    void "Test API wihtout Api Key XML"() {
        when:
            params.outputFormat = "xml"
            withFilters(action: "customer") {
                controller.someAction()
            }
        then:
            println "Response from Server " + response.text?.toString()
            println "Test 1 " + response?.getRedirectUrl()
            println "Test 2 " + response?.getRedirectedUrl()
            println "Test 3 " + response?.text
            println "Test 4 " + response.contentType
            def xmlSlurperInstance = new XmlSlurper()
            xmlSlurperInstance?.setFeature("http://ift.tt/WV2C4M", false)
            xmlSlurperInstance?.setFeature("http://ift.tt/1pbdJzG", false)
            def inputStream = new ByteArrayInputStream(response.text?.toString()?.getBytes())
            def testXMLArray = xmlSlurperInstance?.parse(new InputSource(inputStream))
            response.contentType == "text/xml"
    }
}

On Output "Test 3", nothing is visible, though here should be the content which i render from the filter... it also is the same response if i code the Filter to redirect to another controller in the namespace "api", which will handle the render task.

Anyone experienced something similar already or may know a workaround to get the expected result?

Test if super() was called during initialization gives AttributeError

I would like to test if in the following scenario the init routine of the Base class is called during the initialization of the Derived class:

class Base(object):
    def __init__(self, a):
        self.a = a

class Derived(Base):
    def __init__(self, a):
        super(Derived, self).__init__(a)

I used this post here and this test works fine:

@mock.patch("mocktest.Base.__init__")
def test_calls_init_routine_of_base(mock_super_init):
    Derived(1)
    assert mock_super_init.called

However, if the Derived class does something with the attribute a after super(Derived, self).__init(a), e.g. if I put a print(self.a) right after the call to super(), then the test throws an AttributeError:

AttributeError: 'Derived' object has no attribute 'a'

How can I prevent this? Are there other/better ways to realize this test in this situation?

Unit testing of a very dynamic web application?

My business web application (PHP with HTML/Javascript) has lots of very different options (about 1000) which are stored in the database, so the users can change them theirselves. These options for example define if a button, tab or inputfield is visible, the validation of inputs and the workflow, like when e-mails should be sent.

My users can use any combination of these options, so I find it very difficult to write tests for all these situations. I have 100+ customers so writing tests for each customer is definetely not an option.

The problem is that some options work together. So while testing one option it's necessary to know the value of some other options. Ideally the tests should also be able to read the options-profiles for each customer. But that would almost be like rewriting the whole application, just for testing, which seems error-prone by itself.

Is it common in unit testing to read the database to get the test-data and options, or is that not a good idea?
How would you handle the situation I described ?

How to mock Cache::remember in Laravel

Within a unit test method, I tried to mock a Cache::remember response like this:

Cache::shouldReceive('remember')
    ->once()
    ->with('my_key', 120, function() {}) // There are 3 args in remember method
    ->andReturn([]);

But I get this error:

exception 'Mockery\Exception\NoMatchingExpectationException' with message 'No matching handler found for Mockery_0_Illuminate_Cache_CacheManager::remember ("my_key", 120, object(Closure)). Either the method was unexpected or its arguments matched no expected argument list for this method

I don't understand why I got this error and did not found anything in Laravel documentation about this. It says there is no matching, but it seems to match.

How can I mock a mock a Cache::remember response?

Is there a way to get the real data for karma unit tests with services?

I would like to test an angular service - e.g.:

'use strict';

angular
    .module('com.attributes.services', [])
    .service('krAdminAttributeService', [
        '$rootScope',
        '$http',
        function ($rootScope, $http) {
                var modelData = {
                    "type": "",
                    "groupId": "",
                    "unit": "",
                    "description": "",
                    "name": {}
                };

                var service = {
                    mapAttributes: function (results, update) {
                        if (!update) {
                            modelData.identifier = results.identifier;
                        }
                        modelData.type = results.type;
                        modelData.groupId = results.groupselect;
                        if (results.unit !== undefined) {
                            modelData.unit = results.unit;
                        }

                        modelData.description = results.description;
                        //Name
                        modelData.name = {
                            i18n: true,
                            key: "klapi.attribute:" + results.identifier + ".name"
                        };
                        modelData = angular.copy(modelData);
                    },
                    get: function (params) {
                        //return the promise directly.
                        return $http.get($rootScope.globals.API + 'Attributes', {params: params}).then(function (result) {
                            return result.data;
                        });
                    },
                    getId: function (id) {
                        //return the promise directly.
                        return $http.get($rootScope.globals.API + 'Attributes/' + id + "?filter[include]=group").then(function (result) {
                            return result.data;
                        });
                    },
                    update: function (results) {
                        this.mapAttributes(results, true);
                        return $http.put($rootScope.globals.API + "Attributes/" + results.id, JSON.stringify(modelData), $rootScope.globals.CONFIG).then(function (result) {
                            return result;
                        });
                    },
                    updateName: function (params) {
                        return $http({
                            method: 'POST',
                            url: $rootScope.globals.I18NAPI + "change/de/klapi.attribute",
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            transformRequest: function (obj) {
                                var str = [];
                                for (var p in obj)
                                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                                return str.join("&");
                            },
                            data: params
                        }).then(function (result) {
                            return result;
                        });
                    },
                    add: function (results) {
                        this.mapAttributes(results, false);
                        return $http.post($rootScope.globals.API + "Attributes", JSON.stringify(modelData), $rootScope.globals.CONFIG).then(function (result) {
                            return result;
                        });
                    },
                    delete: function (id) {                        
                        // post(url, data, [config]);
                        return $http.delete($rootScope.globals.API + "Attributes/" + id, $rootScope.globals.CONFIG).then(function (result) {
                            return result;
                        });
                    }
                };
                return service;
            }]);

My test looks like this:

describe("krAdminAttributeService", function () {
    var krAdminAttributeService,
    $q,
    rootScope,
    httpBackend;



    beforeEach(function () {
        module('app');
        inject(function($httpBackend, _krAdminAttributeService_, _$q_, $rootScope) {
            krAdminAttributeService = _krAdminAttributeService_;
            httpBackend = $httpBackend;
            rootScope = $rootScope.$new();
            $q = _$q_;
        });
    });

    // check to see if it has the expected function
    it('should have a get function', function () {
        expect(angular.isFunction(krAdminAttributeService.get)).toBe(true);
    });
    it('should have a getId function', function () {
        expect(angular.isFunction(krAdminAttributeService.getId)).toBe(true);
    });
    it('should have an update function', function () {
        expect(angular.isFunction(krAdminAttributeService.update)).toBe(true);
    });
    it('should get the attributes', function () {
        var data;
        var response = {id:"12345"};
        httpBackend.whenGET('http://localhost:3000/api/Attributes').respond(200,response);
        // set up a deferred
        var deferred = $q.defer();
        // get promise reference
        var promise = deferred.promise;

        // set up promise resolve callback
        promise.then(function (response) {
            console.log('data',response);
            data = response;
        });
        krAdminAttributeService.get().then(function(response) {
            // resolve our deferred with the response when it returns            
            deferred.resolve(response);
            console.log('response', response);

        });
        httpBackend.flush();

        // make your actual test
        //expect(data).toEqual(200);

    });
});

The problem is, that this unit test is not retrieving the actual data but just some mocked data (in this case {id:'12345'}). For me, that makes the test less useful. Is there a way to test with real data? (CORS available)

MS Unit Framework for C++

I am using MS unit framework to write unit tests in VS2013.

I have following questions - 1. How to write unit tests for global functions ? 2. How to write unit tests for static member functions of a class ? 3. How to write unit tests for overloaded member functions of a class ?

Lets say i have 2 class fuctions as - void fun(); void fun (int a);

How to write unit test for above example ?

Ref link http://ift.tt/1NEbrD8

Regards, Parikshit.

mardi 29 décembre 2015

Python3 Relative Imports inside a package

I realize that there are a lot of questions about this on StackOverflow already, but I find the solutions to be entirely unclear and often contradicting of each other.

I have the following scenario: I am writing a python (Python 3.4) package with the following structure:

mypackage/
    __init__.py (empty file)
    mydir1/
        __init__.py (empty file)
        mymodule1.py
    mydir2/
        __init__.py (empty file)
        mymodule21.py
        mymodule22.py
    mydir3/
        __init__.py (empty file)
        mymodule31.py
        mymodule32.py
    tests/
        __init__.py (empty file)
        test_something_in_mydir1.py
        test_something_in_mydir2.py
        test_something_in_mydir3.py

I want the files within the tests/ directory to contain unit tests of everything inside the package. The problem is that no matter which approach I try, I get this error:

SystemError: Parent module '' not loaded, cannot perform relative import

I should note that I want this to work "out of the box" which means that I do not want to import things using their absolute paths and I do not want to change my path variable. None of these solutions seem very pythonic and its driving me slowly up the wall. Is there really no way to do this?

I've tried a bunch of stuff already, including examples below, but they all seem to produce the same result:

from ..mydir1.mymodule1 import *
from .mypackage.mydir1.mymodule1 import *
from ...mypackage.mydir1.mymodule1 import *

And I've tried overwriting the __all__ variable in each of the __init__.py files as well as doing the imports as shown here: http://ift.tt/1mQ7rts

Can anyone tell me how to structure the imports (for example) in the file test_something_in_mydir1.py in such a way as to have access to all the classes/functions that are found in mymodule1.py for unit testing the package?

Does the OR operator cause an DisconnectedContext exception when used in a if statement?

Well yeah, does the OR operator cause an DisconnectedContext exception when used like this:

bool l = driver.Url.Contains("something");
bool l2 = driver.FindElement(By.CssSelector("#Csssomthing")).IsElementVisible();
if (l || l2)
{
    //do something 
}

public static bool IsElementVisible(this IWebElement element)
    {
        return element.Displayed && element.Enabled;
    }

It throws the DisconnectedContext exception the moment it reaches bool l2 and the unit test fails, so can any one tell me what the issue actually is?

Python mock attributes defined and set within __init__

I am trying to write some unit tests for an application and I using python mock. I am familiar with other mocking libraries and haven't had much trouble until now. I am trying to mock a chained call on an attribute set within the init block of the parent class. Here is an example of what I need:

class ApplicationUnderTest:

    def __init__(self):
      self.attributeBeginningChain = SomeClass(False)

    def methodWithChain(self):
      object = self.attributeBeginningChain.methodOfSomeClass()

I need the chained call to throw an error. I have tried resolving this in the following manner:

@patch.object(SomeClass(False), 'methodOfSomeClass', side_effect=ErrorClass)
def test_chained_call(self, mock_someclass):
    A = ApplicationUnderTest.methodWithChain()
    self.assertTrue(mock_someclass.called)

The last assertion fails so I am pretty sure this isn't the way to do this. I have also tried:

@patch('ApplicationUnderTest.attributeBeginningChain')
def test_chained_call(self, mock_someclass):
    mock_someclass.methodOfSomeClass.side_effect = ErrorClass
    A = ApplicationUnderTest.methodWithChain()
    self.assertTrue(mock_someclass.called)

That throws the error:

AttributeError: package.ApplicationUnderTest does not have the attribute 'attributeBeginningChain'

I cannot make alterations to the code under test, so my question is how can I mock chained calls made on attributes set under the _init__ function? I have read that this is not possible but surely there must be a work around? Can I perhaps somehow instruct the mock fixture to react to the call itself rather than the attribute object via autospec?

Are OCMock objects really instances of a class?

When we create a mock object with OCMock, for example

id classMock = OCMClassMock([SomeClass class]);

is the classMock a real object of SomeClass in the background, or is it some sort of a hack?

Thanks.

Unit Testing A Web API That Uses Windows Authentication

Here's my situation. I have a Web API in an intranet site that populates a dropdown. The query behind the dropdown takes the windows username as a parameter to return the list.

I realize I don't have all of this set up correctly because I'm not able to unit test it. I need to know how this "should" be set up to allow unit testing and then what the unit tests should look like.

Additional Info - This is an ASP.NET MVC 5 application.

INTERFACE

public interface ITestRepository
{
    HttpResponseMessage DropDownList();
}

REPOSITORY

public class TestRepository : ITestRepository
{
    //Accessing the data through Entity Framework
    private MyDatabaseEntities db = new MyDatabaseEntities();

    public HttpResponseMessage DropDownList()
    {
        //Get the current windows user
        string windowsUser =  HttpContext.Current.User.Identity.Name;

        //Pass the parameter to a procedure running a select query
        var sourceQuery = (from p in db.spDropDownList(windowsUser)
                           select p).ToList();

        string result = JsonConvert.SerializeObject(sourceQuery);
        var response = new HttpResponseMessage();
        response.Content = new StringContent(result, System.Text.Encoding.Unicode, "application/json");

        return response;            
    }
}

CONTROLLER

public class TestController : ApiController
{
    private ITestRepository _testRepository;

    public TestController()
    {
        _testRepository = new TestRepository();
    }

    [HttpGet]
    public HttpResponseMessage DropDownList()
    {
        try
        {
            return _testRepository.DropDownList();
        }
        catch
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
    }
}

How do we mock fetch for Redux Async Actions?

In the Writing Tests section of Redux,http://ift.tt/1WuLEat, how does the store.dispatch(actions.fetchTodos()) not invoke the fetch method, if store.dispatch is literally calling actions.fetchTodos?

it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] })

const expectedActions = [
  { type: types.FETCH_TODOS_REQUEST },
  { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
]
const store = mockStore({ todos: [] }, expectedActions, done)
store.dispatch(actions.fetchTodos())


})

Tests passes but failures displayed as well in Mocha.js

I'm wondering why my tests are both passing but with failures. Tests passes with failures

The code that is used to tests features is:

var fireHotKey = function (key) {
    var event = document.createEvent('HTMLEvents'),
        input = document.querySelector(SELECTOR_INPUT);

    event.keyCode = key;
    event.initEvent('keyup', false, true);
    input.dispatchEvent(event);
};

it('Should create a new tag based on user input', function (done) {
    var input = document.querySelector(SELECTOR_INPUT),
        tagsContainer = document.querySelector(SELECTOR_TAGS),
        tagName = 'sunpietro';

    input.value = tagName;

    fireHotKey(KEY_COMMA);

    document.addEventListener(EVENT_TAGS_CREATED, function () {
        expect(tagsContainer).to.contain(SELECTOR_TAG);
        expect(tagsContainer.querySelectorAll(SELECTOR_TAG)).to.have.length(1);

        done();
    });
});

What is done incorrectly?

How do we mock fetch in Redux Async Actions?

In the Writing Tests section of Redux,http://ift.tt/1WuLEat, how does the store.dispatch(actions.fetchTodos()) not invoke the fetch method, if store.dispatch is literally calling actions.fetchTodos?

it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] })

const expectedActions = [
  { type: types.FETCH_TODOS_REQUEST },
  { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
]
const store = mockStore({ todos: [] }, expectedActions, done)
store.dispatch(actions.fetchTodos())


})

Everytime I try to run something similar to this, I keep getting a fetch is not defined. Even if I use nock. So I have to spy my action to not get the call to fetch.

Here is my unit test:

it('should request a password reset, and then return success on 200', (done) => {
        nock('http://localhost:8080/')
        .post('password-reset-requests')
        .reply(200);


var email = "test@email.com";
        const expectedActions=[
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];
        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest());

here is the action:

export default function addPasswordResetRequest(email){
    return dispatch => {
        dispatch(requestAddPasswordResetRequest(email));
        return addPasswordResetRequestAPI(email)
            .then(() =>{
                dispatch(requestAddPasswordResetRequestSuccess());
            })
            .catch((error) => {
            dispatch(requestAddPasswordResetRequestFailure(error));
        });
    };
}

and the function that calls fetch:

export const addPasswordResetRequestAPI = (email) => {
    return fetch(
        SETTINGS.API_ROOT + '/password-reset-requests',
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                code: NC_SETTINGS.GROUP.code
            })
        }
    )
        .then(handleResponse);
};

I'm not sure if the way I am doing is sufficient for the purpose of just testing actions, but then I do run into the problem of store.dispatch only returning the first element of expectedActions, and it doesn't equal the list I supply in the spied addPasswordResetRequest. Below includes the spied action.

it('should request a password reset, and then return success on 200', (done) => {
        nock('http://localhost:8080/')
        .post('password-reset-requests')
        .reply(200);
        Actions.addPasswordResetRequest = spy(() => {
    return ([
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ]
        );
});
        var email = "test@email.com";
        const expectedActions=[
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];

        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest());

Why is my WCF service not working in Test Project?

Something strange is happening. I have a WCF service using C# and Visual Studio 2015 up and running.

This service is published to my local IIS and I have a test website where I can consume my services and display results. The website is running in the visual studio IIS on a generated port.

I have a test project which is where I'm experiencing a problem. In the test project I run the same code that works in the website. However when I debug it my wcf result is already out of context.

  • The test fails
  • The service result 'does not exist in the current context' when debugging.

        [TestMethod]
        public void Test_GetListOfFastPlans()
        {
            FastPlanFileShareServiceClient client = new FastPlanFileShareServiceClient();
    
            ListSharedFastPlansResult thisismyresult = client.ListOfSharedFastPlans("asdf", "asdf", null, null, null, false);
    
            Assert.IsTrue(thisismyresult.ServiceResult.WasSuccessful);
        }
    
    

I can step through the entire code block from creating the client to making the call and finally the assertion without any errors. however, the resultclass and the client are never in context.

I don't know what is happening or how to diagnosis the issues.

Use Guice to create components to use with ThreadWeaver

The application I have been working on has been getting more and more complicated, and it's gotten to the point where I have been running into the same problems over and over again with concurrency. It no longer made any sense to solve the same problems and not have any regression tests.

That's when I found ThreadWeaver. It was really nice for some simple concurrency cases I cooked up, but I started to get frustrated when trying to do some more complicated cases with my production code. Specifically, when injecting components using Guice.

I've had a bit of a hard time understanding the implications of the way ThreadWeaver runs tests, and looked for any mention of Guice or DI in the wiki documents, but with no luck.

Is Guice compatible with ThreadWeaver?

Here is my test

@Test
public void concurrency_test() {
    AnnotatedTestRunner runner = new AnnotatedTestRunner();
    runner.runTests(OPYLWeaverImpl.class, OPYLSurrogateTranscodingService.class);
}

Here is my test implementation

public class OPYLWeaverImpl extends WeaverFixtureBase {

@Inject private TaskExecutor                 taskExecutor;
@Inject private Serializer                   serializer;
@Inject private CountingObjectFileMarshaller liveFileMarshaller;
@Inject private GraphModel                   graphModel;
@Inject private CountingModelUpdaterService  updaterService;
@Inject private BabelCompiler                babelCompiler;
@Inject private EventBus                     eventBus;

OPYLSurrogateTranscodingService service;

private Path testPath;

@ThreadedBefore
public void before() {
    service = new OPYLSurrogateTranscodingService(eventBus, taskExecutor, serializer, liveFileMarshaller,
            () -> new OPYLSurrogateTranscodingService.Importer(graphModel, babelCompiler, updaterService, eventBus),
            () -> new OPYLSurrogateTranscodingService.Validator(eventBus, babelCompiler),
            () -> new OPYLSurrogateTranscodingService.Exporter(graphModel, updaterService));
}

@ThreadedMain
public void mainThread() {
    testPath = FilePathOf.OASIS.resolve("Samples/fake-powershell-unit-test.opyl");
    service.applyToExistingGraphModel(testPath);
}

@ThreadedSecondary
public void secondaryThread() {

}

@ThreadedAfter
public void after() {

}

And the WeaverFixtureBase

public class WeaverFixtureBase {
@Inject protected CountingEventBus eventBus;

@Before public final void setupComponents() {
    Injector injector = Guice.createInjector(new WeaverTestingEnvironmentModule(CommonSerializationBootstrapper.class));
    injector.getMembersInjector((Class) this.getClass()).injectMembers(this);
}
private class WeaverTestingEnvironmentModule extends AbstractModule {

    private final Class<? extends SerializationBootstrapper> serializationBootstrapper;

    public WeaverTestingEnvironmentModule(Class<? extends SerializationBootstrapper> serializationConfiguration) {
        serializationBootstrapper = serializationConfiguration;
    }

    @Override protected void configure() {
        bind(TaskExecutor.class).to(FakeSerialTaskExecutor.class);
        bind(SerializationBootstrapper.class).to(serializationBootstrapper);
        bind(ModelUpdaterService.class).toInstance(new CountingModelUpdaterService());
        bindFactory(StaticSerializationConfiguration.Factory.class);

        CountingEventBus localEventBus = new CountingEventBus();

        bind(Key.get(EventBus.class, Bindings.GlobalEventBus.class)).toInstance(localEventBus);
        bind(Key.get(EventBus.class, Bindings.LocalEventBus.class)).toInstance(localEventBus);
        bind(CountingEventBus.class).toInstance(localEventBus);
        bind(EventBus.class).toInstance(localEventBus);

    }
    @Provides
    @Singleton
    public GraphModel getGraphModel(EventBus eventBus, Serializer serializer) {
        return MockitoUtilities.createMockAsInterceptorTo(new GraphModel(eventBus, serializer));
    }
}

But when the classloader loads OPYLWeaverImpl, none of the Guice stuff goes off and I get a big pile of nulls.

I feel like this is one of those "missing-something-really-simple" kind of scenarios. Sorry if it is!

JavaScript and AngularJS testing - Karma, Jasmine, karma-jasmine, etc

I'm preparing some curriculum for students at a bootcamp, and this is my first exposure to testing in general, let alone testing in Angular. I've been researching a lot of stuff, but thought I could get some definitive answers from the community:

I'm still a little hazy on how Karma and Jasmine work together. I understand that Karma is a test runner and Jasmine is the framework that includes assertions, describe blocks, etc. But what is the best/preferred way to install these to start including testing in an Angular app? I've done npm install --save-dev karma, run karma init and set all the settings, and downloaded Jasmine from their releases page, but I'm not exactly sure how to integrate these into a new or existing Angular application. The Jasmine Standalone seems to have its own organization that requires you to move all your source files to their src folder, but that seems ridiculous unless you're just testing vanilla JavaScript (which I'm guessing is what the Jasmine standalone version is for?)

I also saw in the Angular docs on testing a reference to karma-jasmine, which I'm not 100% sure how that plays in with karma and jasmine as separate entities.

Any guidance or help for a testing beginner would be greatly appreciated. I've spent hours researching and am still a bit confused on all of it. Sorry if these questions are dumb, I'm really new to the whole concept.

Thanks in advance for your help!

Using the Python mock module, how can I patch a class so that it stubs only the methods I want to stub and leaves other properties and methods alone?

Here's a simple case that shows what I want (Python 2.7). (Note: in my actual use case, MyClass is a class that gets instantiated indirectly within some code I'm testing):

from mock import patch

class MyClass(object):
    def __init__(self):
        self.prop = 'prop'

    def foo(self):
        return 'foo'

    def bar(self):
        return 'bar'

patcher = patch('__main__.MyClass')
MockedClass = patcher.start()
instance = MockedClass.return_value
instance.foo.return_value = 'mocked foo!'

my_instance = MyClass()
assert my_instance.foo() == 'mocked foo!', my_instance.foo()

# These asserts will fail
assert my_instance.bar() == 'bar', my_instance.bar()
assert my_instance.prop == 'prop', my_instance.prop

patcher.stop()

What I'm getting instead:

$ python mock_test.py
Traceback (most recent call last):
  File "mock_test.py", line 22, in <module>
    assert my_instance.bar() == 'bar', my_instance.bar()
AssertionError: <MagicMock name='MyClass().bar()' id='140162491496976'>

Why is the bar method now returning a MagicMock object? How can I patch this class so it stubs only the methods I want and leave everything else alone?

Loading Related Entities in Mocked DbContext using Moq for Web Api 2 Controller Tests

I'm trying to unit test some Web Api 2 Controllers that use Entity Framework 6 but having issues with the loading of the related entities after the entity has been added. I'm using Moq to create a mocked DbContext and DbSet, and have added

public virtual void MarkAsModified<T>(T item) where T : class
{
   Entry(item).State = EntityState.Modified;
}

to get around the _db.Entry(foo).State = EntityState.Modified; issue on a Put action.

The Api Action is a Post in this simplified example where we need to get back 2 related entities (Bar and Qux).

[ResponseType(typeof (Foo))]
public async Task<IHttpActionResult> PostFoo(Foo foo)
{
  if (!ModelState.IsValid)
  {
     return BadRequest(ModelState);
  }
  //Do other stuff
  _db.Foos.Add(foo);
  _db.Entry(foo).Reference(x => x.Bar).Load();
  _db.Entry(foo).Reference(x => x.Qux).Load();
  await _db.SaveChangesAsync();
  return CreatedAtRoute("DefaultApi", new {id = foo.Id},foo);
}

And then a simplified test would be

[TestMethod]
public async Task PostFoo()
{
  var model = new Foo
  {
    Name="New Foo",
    QuxId = 99,
    Qux = null,
    BarId = 66,
    Bar = null
  };
 var result = await _controller.PostFoo(model) as CreatedAtRouteNegotiatedContentResult<Foo>;
 Assert.IsNotNull(result);
 Assert.IsNotNull(result.Qux);
 Assert.IsNotNull(result.Bar);
}

Is there a more mock-friendly way of doing _db.Entry(foo).Reference(x => x.Bar).Load();

What is the purpose of Redux Async Action Testing?

Could someone explain why we test asynchronous actions? What are we hoping to ensure works?

So in the docs, http://ift.tt/1WuLEat, we mock the server request.

nock('http://example.com/')
  .get('/todos')
  .reply(200, { todos: ['do something'] })

const expectedActions = [
  { type: types.FETCH_TODOS_REQUEST },
  { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
]
const store = mockStore({ todos: [] }, expectedActions, done)
store.dispatch(actions.fetchTodos())

So we aren't testing to see if we contact the server. We are testing to see if the correct sequence of actions takes place, given a response of 200 correct?

How to test enum validation?

I have a variable that has a specific set of answer options. In my model I have:

validates :article_type,  presence: true
enum article_type:        [ :type1, :type2, :type3 ]

I have the following model test:

test "type test" do
  assert @article.valid?
  @article.article_type= "type1"
  assert @article.valid?
  @article.article_type= "type5"
  assert_not @article.valid?
end

Error: The line @article.article_type= "type5" generates the error: ArgumentError: 'type5' is not a valid article_type.

For all other sorts of validations where I include invalid data and then use assert_not these kinds of tests work. Why not in this case? How should I rewrite this model test?

Unit test an WF activity that connects to an database

I have a WF activity that takes in a server name, database name as arguments and connects to a database to fetch some data.

I need to unit test this activity, but I need some ideas... since I only have the server and database name. usually the mocking frameworks create the actual data objects and not the "server" and "database".

Any ideas?

Thanks

Mockito Spy - partial mocking not working?

My scenario is pretty simple. Trying to use partial mocks, according to last answer on this and the documentation of Mockito itself. My test is:

@Test
public void test() {
    ClassUnderTest realObject = new ClassUnderTest();
    ClassUnderTest spy = spy(realObject);
    when(spy.methodB()).thenThrow(new Exception("Testing"));


    spy.methodA();
}

and the class under test is:

import org.apache.commons.lang3.NotImplementedException;

public class ClassUnderTest {

    int methodB(){
        throw new NotImplementedException("Not implemented");
    }

    public int methodA(){
        methodB();
        return 0;
    }

}

I would expect that my spying object would call the method B raising the "Testing" exception while actually the real method is called throwing the "Not implemented" exception. It behaves like I don't have a partial mock behavior in place

Why is that? What am I missing?

Mock Date object using Mockito

A method of MyService class returns java.util.Date object and MyManager class is calling that method of MyService class. I am writing the test case for MyManager class.
when I mock

Mockito.when(manager.getDate())).thenReturn((Date)Mockito.any())

is not working. Could some one help me on this please?

TestNG test class for a well encapsulated class

I am unit testing a class with the following structure.

public class Experiment {

    private final Map<String,String> map = new HashMap<>();

    Experiment(Set<String> set){
        for(String str :set ){
            map.put(str,str);
        }
    }

    public String getVal(String str){
        return map.get(str);
    }

}

As seen my class has only one instance variable that is a HashMap. Now i want to make sure my map is correctly populated through my constructor which takes a HashSet. Since I can create a expected Map structure independently. But i am stuck now because my 'map' is "private" in my class. I dont want to expose my state variable to outside world by making it public. Please suggest a way to Unit test my map variable.

Unit test: Could not find data file if it is inside a folder

I am creating data driven unit testing method which uses xml to pass data. I have followed examples which are given in SO and MS website and created a method accordingly.

I have created one xml file inside a directory data in my project. So the path is /data/d.xml. I have set Copy to Output Directory property as Copy always. The problem I am facing here is, the file is being copied to the directory Debug\data\d.xml, but, my unit test method is trying to find it in Debug\d.xml.

How to make my unit test method to find that file in Debug\data\d.xml or How to make my data file moved directly under Debug folder without moving it out of the data directory?
My unit test method is as follows,

    [TestMethod]
    [DeploymentItem("d.xml")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "/data/d.xml", "model", DataAccessMethod.Sequential)]
    public void GetCPCModelTest()
    {
        //some code
        Assert.IsTrue(model != null);
    }

Android ServiceTestCase run service by context

I've got class which serves as a public API for the lib I've written. Now I want to write unit tests and call the methods of that class, here is the snippet of it:

public final class Analytics {

    public static void init(Context context,
                            @NonNull String appId,
                            @NonNull String deviceID,
                            @NonNull String countryCode,
                            @NonNull String market) {
        Intent analyticsIntent = new Intent(context, PAanalyticsService.class)
                .putExtra("app_id", appId)
                .putExtra("device_id", deviceID)
                .putExtra("country_code", countryCode)
                .putExtra("market", market);

        context.bindService(analyticsIntent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        }, Context.BIND_AUTO_CREATE);
    }

    public static void setUserId(Context context, long userId) {
        Intent intent = new Intent(context, PAanalyticsService.class)
                .setAction(Constants.UPDATE_USER_ACTION)
                .putExtra("user_id", userId);

        context.startService(intent);
    }
}

The problem is that in my methods service is started by context, so if I call Analytics class methods from my unit tests service won't be run, I must call startService()/bindService of ServiceTestCase for running PAanalyticsService, but in that case I lose the opportunity to call the methods of my class.

jasmine beforeAll affected by sibling describe

I was under the impression that the beforeAll-function would run once for the describe it was inside. However it seems that sibling describes can affect the beforeAll.

the following tests can be found here

describe("outer Describe", function(){
    var testArray;
    beforeEach(function(){
      testArray = [];
    });
    describe("First Describe", function(){
      beforeEach(function(){
        testArray.push({name: "foo"});
      });

      it("has an item", function(){
        expect(testArray.length).toBe(1);//passing
      });
    });

    describe("Second describe", function(){
      var arrIsEmptyInBeforeAll;
      var arrIsEmptyInBeforeEach;
      beforeAll(function(){
        arrIsEmptyInBeforeAll = testArray.length === 0;
        console.log("testArray should be empty:");
        console.log(testArray);//logs array with one item
      });

      beforeEach(function(){
        arrIsEmptyInBeforeEach = testArray.length === 0;
      });

      it("the arr was empty in before all", function(){
        expect(arrIsEmpty).toBeTruthy(); //This is failing
      });

      it("the arr was empty in beforeEach", function(){
        expect(arrIsEmptyInBeforeEach).toBeTruthy();//Passing
      })
    })
  });

I would expect that the beforeAll inside the "Second Describe" would have an empty testArray, because the "outer Describe" has a beforeEach that initializes it as an empty array. However, in the beforeAll of "Second Describe", the testArray has the one item added in "First Describe"'s beforeEach.

Does this make sense? If so, could someone explain how beforeAll is supposed to work.

lundi 28 décembre 2015

How to test a directive which uses ngModel on same element

I have a directive which requires ngModel. In its link function it calls $setViewValue on the ngModel controller. I want to test that $setViewValue is being called under the right conditions, but I can't work out how to add my spy...

Here is my simplified code:

directive

angular.module("myApp").directive("myDir", function()
{
    return {
        restrict: "A",
        require: ["ngModel"],
        link: function(scope, element, attrs, ctrls)
        {
            var ngModel = ctrls[0];

            ......

            function changeHandler(event) {
                ngModel.$setViewValue(ckeditor.getData());
            }
        }
    };
});

html:

<textarea my-dir ng-model="myData"></textarea>

and I want my test to be something like:

describe("updating text in ckeditor", function() {
        it("should update model value", function() {
                $compile("<textarea my-dir ng-model='text'></textarea>")(scope);
                spyOn(ngModel, "$setViewValue");
                // trigger change handler
                expect(ngModel.$setViewValue).toHaveBeenCalled();
        });
});

Thanks!

Android: PowerMockito Static JUnit Tests

I am currently writing Unit Tests for my bluetooth class.

Here is the method that I am currently on:

@VisibleForTesting
protected static Looper getConnectionTimeoutLooper() {
    HandlerThread handlerThread = new HandlerThread("BM-ConnectionTimeoutThread");
    handlerThread.start();
    return handlerThread.getLooper();
}

Here is what my Unit Test is looking like based on this StackOverflow post.

@Test
public void getConnectionTimeoutLooper_ReturnLooper() throws Exception {
    Looper mockLooper = mock(Looper.class);
    PowerMockito.mockStatic(BluetoothManager.class);
    BDDMockito.given(BluetoothManager.getConnectionTimeoutLooper()).willReturn(mockLooper);


    BluetoothManager.getConnectionTimeoutLooper();

    PowerMockito.verifyStatic();
    BluetoothManager.getConnectionTimeoutLooper();
}

I am now stumped. Please can someone assist me with this test.

Thanks

How can I use Mocha to unit-test a React component that paints on a ?

I have a React component that uses a <canvas> for user interaction. I'm not using react-canvas or react-art or anything like that; instead, I just draw on the canvas's 2D context in componentDidMount and componentDidUpdate.

I extracted as much of the logic as possible to two separate modules: one comprises entirely pure functions and provides the core operations independent of React, and the other provides event handlers and lifecycle mixins to be attached to the React component. I can test the first one easily, and the second one with a bit of mocking.

However, I'd also like to very minimally test the main canvas component just to make sure that it can render with no errors given some reasonable set of props. This is proving rather difficult because componentDidMount calls this.refs.canvas.getContext('2d'), which doesn't appear to be defined in the node environment. So I came up with the following solution, which I don't like very much; it involves both patching React.createElement and creating a fake context object:

// file: test/components/MyCanvasTest.jsx
import {describe, it} from 'mocha';
import {expect} from 'chai';

import React, {Component} from 'react';

import {declareMochaMock} from '../TestUtils';
import {
    renderIntoDocument,
    scryRenderedDOMComponentsWithTag,
} from 'react-addons-test-utils';

import MyCanvas from '../../src/components/MyCanvas';

describe('MyCanvas', () => {

    const noop = () => {};

    // These things are used in my component
    // but I don't want them to actually do anything,
    // so I mock them as no-ops.
    const propsToMockAsNoop = [
        'addEventListener',
        'removeEventListener',
        'setInterval',
        'clearInterval',
    ];
    propsToMockAsNoop.forEach(prop => declareMochaMock(window, prop, noop));

    // This thing is used in my component
    // and I need it to return a dummy value.
    declareMochaMock(window, 'getComputedStyle', () => ({ width: "720px" }));

    // This class replaces <canvas> elements.
    const canvasMockClassName = 'mocked-canvas-component';
    class CanvasMock extends Component {
        render() {
            return <div className={canvasMockClassName} />;
        }
        constructor() {
            super();
            this.width = 720;
            this.height = 480;
        }
        getContext() {
            // Here I have to include all the methods
            // that my component calls on the canvas context.
            return {
                arc: noop,
                beginPath: noop,
                canvas: this,
                clearRect: noop,
                fill: noop,
                fillStyle: '',
                fillText: noop,
                lineTo: noop,
                measureText: () => 100,
                moveTo: noop,
                stroke: noop,
                strokeStyle: '',
                textAlign: 'left',
                textBaseline: 'baseline',
            };
        }
    }

    const originalCreateElement = React.createElement;
    declareMochaMock(React, 'createElement', (...args) => {
        const newArgs = args[0] === 'canvas' ?
            [CanvasMock, ...args.slice(1)] :
            args;
        return originalCreateElement.apply(React, newArgs);
    });

    it("should render a <canvas>", () => {
        const element = <MyCanvas />;
        const component = renderIntoDocument(element);
        expect(scryRenderedDOMComponentsWithTag
            (component, canvasMockClassName)).to.have.length(1);
    });

});

The declareMochaMock function is defined as

// file: test/TestUtils.js
export function declareMochaMock(target, propertyName, newValue) {
    let oldExisted;
    let oldValue;
    before(`set up mock for '${propertyName}'`, () => {
        oldValue = target[propertyName];
        oldExisted = Object.prototype.hasOwnProperty.call(
            target, propertyName);
        target[propertyName] = newValue;
    });
    after(`tear down mock for '${propertyName}'`, () => {
        if (oldExisted) {
            target[propertyName] = oldValue;
        } else {
            delete target[propertyName];
        }
    });
}

I can't use a shallow renderer because my component accesses the canvas via a ref, and refs aren't yet supported in the shallow renderer.

Is there a way to approach this test with my current unit testing frameworks (i.e., not adding Jest or anything like that) while reducing the amount that the test harness needs to know about?

(The full canvas component is available here.)

Test framework in Spring Amqp

Is there any test framework around Spring Amqp , I have explored lots of areas but couldn't find one

cmocka malloc testing OOM and gcov

I'm having a hard time finding an answer to a nitch case using cmocka, testing malloc for failure (simulating), and using gcov

I've tried a myriad combinations mostly based off of two main ideas:

I tried using -Wl,--wrap=malloc so calls to malloc are wrapped. From my cmocka tests I attempted to use will_return(__wrap_malloc, (void*)NULL) to simulate a malloc failure. In my wrap function I use mock() to determine if I should return __real_malloc() or NULL. This has the ideal effect, however I found that gcov fails to create gcda files, which is part of the reason with wrapping malloc, so I can test malloc failing AND get code coverage results. I feel I've played dirty games with symbols and messed up malloc() calls called form other compilation units (gcov? cmocka?).

Another way I tried was to us gcc -include using a #define for malloc to call "my malloc" and compile my target code to be tested with mymalloc.c (defining the "my malloc"). So a #define malloc _mymalloc helps me call only the "special malloc" from the target test code leaving malloc alone anywhere else it is called (i.e., leave the other compilation unites alone so they just always call real malloc). However I don't know how to use will_return() and mock() correctly to detect failure cases vs success cases. If I am testing malloc() failing I get what I want, I return NULL from "malloc" based on mock() returning NULL- this is all done in a wrapping function for malloc that is only called in the targeted code. However if I want to return the results of the real malloc than cmocka will fail since I didn't return the result from mock(). I wish I could just have cmocka just dequeue the results from the mock() macro and then not care that I didn't return the results since I need real results from malloc() so the code under test can function correctly.

I feel it should be possible to combine malloc testing, with cmocka and get gcov results.

whatever the answer is I'd like to pull of the following or something similar.

int business_code()
{
    void* d = malloc(somethingCalculated);
    void* e = malloc(somethingElse);
    if(!d) return someRecovery();
    if(!e) return someOtherRecovery();
    return 0;
}

then have cmocka tests like

cmocka_d_fail()
{
    will_return(malloc, NULL);
    int ret = business_code();
    assert_int_equal(ret, ERROR_CODE_D);
}

cmocka_e_fail()
{
    will_return(malloc, __LINE__); // someway to tell wrapped malloc to give me real memory because the code under test needs it
    will_return(malloc, NULL); // I want "d" malloc to succeed but "e" malloc to fail
    int ret = business_code();
    assert_int_equal(ret, ERROR_CODE_E);
}

I get close with some of the #define/wrap ideas I tried but in the end I either mess up malloc and cause gcov to not spit out my coverage data or I don't have a way to have cmocka run malloc cases and return real memory i.e., not reeturn from mock() calls. On one hand I could call real malloc from my test driver but and pass that to will_return but my test_code doesn't know the size of the memory needed, only the code under test knows that.

given time constraints I don't want to move away from cmocka and my current test infrastructure. I'd consider other ideas in the future though if what I want isn't possible. What I'm looking for I know isn't new but I'm trying to use a cmocka/gcov solution.

Thanks