samedi 30 avril 2016

PHPUnit fails testing a custom exception

I am having trouble to test correctly a thrown exception (Is it a namspacing problem).

Here is my custom exception:

<?php
namespace Example\Customexception;

class ResourceNotAvailableException extends \Exception {}

Here the class I am testing:

namespace Example\Lib;

use Example\Customexception\ResourceNotAvailableException;

class Configuration {

    private static $instance;

    private $arrConfig;

    private function __construct($configFile)
    {
        $this->arrConfig = parse_ini_file($configFile, true);
        if ($this->arrConfig == false){
            throw new ResourceNotAvailableException("Config file {$configFile} not available.");
        }   
    }

    public static function getInstance($configFile = "config/config.ini")
    {
        if (self::$instance == null){
            try {
                self::$instance = new Configuration($configFile);
            }
            catch(ResourceNotAvailableException $e) {
                throw $e;
            }
        }
        return self::$instance;
    }

}

And here is my test class:

use Example\Lib\Configuration;

class ConfigurationTest extends PHPUnit_Framework_TestCase {


    /**
     * @expectedException Example\Customexception\ResourceNotAvailableException
     */ 
    function testGetInstanceThrowsException()
    {
        $configuration = Configuration::getInstance("configtestini");       
    }


}

And here is the output I get:

PHPUnit 5.3.2 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 89 ms, Memory: 2.75Mb

There was 1 error:

1) ConfigurationTest::testGetInstanceThrowsException
parse_ini_file(configtestini): failed to open stream: No such file or directory

/home/me/workspace/codeexample/src/Lib/Configuration.php:24
/home/me/workspace/codeexample/src/Lib/Configuration.php:39
/home/me/workspace/codeexample/tests/unit/Lib/ConfigurationTest.php:14

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Please ignore the line numbers in the output because I removed some comments from the code to make it easily readable here.

Thanks

Mockito : Stubbing some methods of spy objects

I'm using Mockito for unit testing a class methods. However, If my test method uses some Helper/Utils class methods then I'm spying on that Helper/Utils class objects.In some cases I also need to stub the spy object methods for checking the exceptions. I use

@Spy
private itemsDetailsHelper

doReturn(null).when(itemsDetailsHelper).getDistinctItemsList(itemDetails);

But the method is not returning null.

Detecting and testing a non responsive server in angular

I have a http request similar to this:

const timeout = $q.defer()
let timedOut = false

setTimeout(() => {
  timedOut = true
  timeout.resolve()
}, 4000)

$http({
  method: 'GET',
  url: 'www.someurl.com',
  timeout: timeout.promise
}).then((response) => {
    return response.data
  })
  .catch(() => {
    if (timedOut) {
      return "server is not responding"
    } else {
      return "some other error"
    }
  })

The purpose of this code is to send an http request, and if after 4 seconds there is no response, the request is cancelled, returning a message that the server is unresponsive.

The problem is that I have no idea how I would test something like this, to see if it actually works. I normally use unit tests with $httpBackend to mock requests, but in this case it would not work. Is this the correct approach?

Android Testing Frameworks clarification

Trying to learn instrumentation testing scenarios. While going over the relevant documentation for the ActivityInstrumentationTestCase2, i learned that we can use the ActivityInstrumentationTestCase2 in conjunction with Espresso to write so called "functional" tests. Or at least that is what i understood from the relevant documentation.

However i ran into something called a ActivityUnitTestCase and a ServiceTestCase, which i had never heard of before. Trying to figure that out led me down a wild goose chase and now i am terribly lost here with so many verbiages to the whole Android testing paradigm.

  1. Considering from a high level that Android testing broadly falls into two buckets: Unit testing and functional testing. Out of the following, which falls under which.

    JUnit, JUnit4, TestCase, AndroidTestCase, ActivityInstrumentationTestCase2, ServiceTestCase, ApplicationTestCase, AndroidTestRunner, AndroidJUnitRunner, AndroidJUnit4

  2. What should be used when?

  3. Do any of them relate to the actual Unit testing (by which i mean POJO testing). I ask this because i have noticed some tutorial links in which the sample test case extends JUnit4/TestCase and is still termed a unit test whereas one of the links below does not extend anything at all and still works as a simple POJO test case. Which raises the question what exactly is the difference between a JUnit4 and simple POJO test class.

References that i have checked so far:

http://ift.tt/1NK22Ad

http://ift.tt/1Eog6IQ

Android Test Frameworks

Robolectric vs Android Test Framework

http://ift.tt/INXpW7

Any ideas, tips much appreciated. Thanks!

Objects.equals for jUnit test

First, I am new to Java, so hopefully this isn't something terribly simple, but I am trying to do some unit-testing and I am not getting the old green light in Eclipse. To my problem:

So, I have two Objects, both of class Fraction and I am simply trying to make sure that my method (multiplyThem) is.... uh... functioning correctly.

Code:

@Test
    public void testMultiplyEm() {
        System.out.println(newFraction.multiplyEm(otherFraction));
        System.out.println(new Fraction(2, 15));
        assertTrue("Multiplication failure", Objects.equals(newFraction.multiplyEm(otherFraction), new Fraction(2, 15)));
    }

In the method multiplyEm, the return type is a Fraction and it multiplies two numerators and two denominators before calling on another function called simplify. Then it returns the simplified Fraction.

I used system.out.println on the two individually and got the exact same thing printed to screen. I know that doesn't always mean they ARE the same, but perhaps Objects.equals isn't what I should be using here. The objects are simply two ints... Fraction x = new Fraction(int y, int z)

I am not sure why this fails the test. Anyone have any ideas? Would be grateful for a way to correctly write a unit test for it!

$controller is undefined for one controller during unit test

I have 2 controllers - main and vendor. main.controller successfully logs in my unit test, while vendor.controller gives me an undefined error with the exact same unit test.

unit test

describe('controllers', () => {
    let vm;

    beforeEach(angular.mock.module('thcmaps-ui'));
    beforeEach(inject(($controller) => {
        vm = $controller('MainController'); // This logs correctly but errors when changed to VendorController
        //vm = $controller('VendorController'); 
    }));

    it('should call stateManagerService when current name is main', () => {
        console.log(vm);
        expect(1).toEqual(1);
    });
});

I don't know if it's a routing issue or something completely different...

index.route.js

export function routerConfig($stateProvider, $urlRouterProvider) {
'ngInject';
$stateProvider
    //mobile
    .state('main', {
        url         : '/',
        templateUrl : 'app/main/main.html',
        controller  : 'MainController',
        controllerAs: 'main',
        resolve : {
            location : function(userDataService){
                return userDataService.getLocation()
                    .then(function(data){
                        return data;
                    });
            }
        }
    })
    .state('mobile', {
        url         : '/m/',
        templateUrl : 'app/main/main.html',
        controller  : 'MainController',
        controllerAs: 'main',
        resolve : {
            location : function(userDataService){
                return userDataService.getLocation()
                    .then(function(data){
                        return data;
                    });
            }
        }
    })
    .state('mobile.vendor', {
        url         : 'v/:slug',
        templateUrl : 'app/vendor/vendor.html',
        controller : 'VendorController',
        controllerAs : 'vendor',
        resolve : {
            data : function($stateParams, vendorDataService){
                return vendorDataService.getVendor($stateParams.slug)
                    .then((vendor) =>{
                        return vendor;
                    })
                    .catch(()=>{
                        //todo error handling
                        //console.log(error);
                    })
            },
            location : function(userDataService){
                return userDataService.getLocation()
                    .then(function(data){
                        return data;
                    });
            }
        }
    })
    //desktop
    .state('map.vendor', {
        url         : 'v/:slug',
        templateUrl : 'app/vendor/vendor.html',
        controller : 'VendorController',
        controllerAs : 'vendor',
        resolve : {
            data : function($stateParams, vendorDataService){
                return vendorDataService.getVendor($stateParams.slug)
                    .then((vendor) =>{
                        return vendor;
                    })
                    .catch(()=>{
                        //todo error handling
                        //console.log(error);
                    })
            },
            location : function(userDataService){
                return userDataService.getLocation()
                    .then(function(data){
                        return data;
                    });
            }
        }
    });


  $urlRouterProvider.otherwise('/');
}

Unit testing with external library in Jasmine

How to unit test your code if it's heavily belongs to external library and within each of its methods it calls some external library function. If everything to mock, than code coverage like Istanbul don't count those lines mocked. Who has experience in unit testing with involvement of external dependencies and libraries, what is the best practice?

For instance, we have 2 internal functions and 3 external library functions. If mock those external ones, than Istanbul doesn't count those lines as covered.

function internalFoo1(input) {
 var result = internalFoo2(input*2);
 var finalResult = externalLibraryBar1(result);
 return result;
};

function internalFoo2(value) {
  var operation = externalLibraryBar2(value*2);
  var response = externalLibraryBar3(operation);
  return response;
}

How to write a test for internalFoo1() so unit test will cover all its code lines, as well internalFoo2() one.

Please confirm/comment on Branch Coverage issue I'm seeing with EclEmma Eclipse Plugin

After running this unit testing using EclEmma Eclipse code coverage plugin, it returns 100% Branch coverage, i.e. 4 out of 4 branches covered, I expect only 2 out of 4 branches covered here i.e. 50% coverage. If I turn out to be correct can anyone suggest a better branch coverage tool please. Thanks in advance.

@Test
public void testTT(){;
    assertTrue(bar(true, true)==3);
}

@Test
public void testFF(){;
    assertTrue(bar(false, false)==8);
}


int bar(boolean cond1, boolean cond2) {
      int answer = 1;
      if (cond1) {
          answer = answer * a();
      } else {
          answer = answer * b();
      }

      if (cond2) {
          answer = answer * c();
      } else {
          answer = answer * d();
      }
    return answer;
    }

private int a(){
    return 1;
}

private int b(){
    return 2;
}

private int c(){
    return 3;
}

private int d(){
    return 4;
}

Unit Tests 'NSInternalInconsistencyException' issue

I want to run my UnitTest, but it fails with the next error:

test failure: -[ToDoItemTests testInit_ShouldTakeTitle()] failed: failed: caught "NSInternalInconsistencyException", "No target application path specified via test configuration: <XCTestConfiguration: 0x7faee9e07380>

How can I fix it and run my tests?

P.S I searched and found that I need to set my target correctly, I checked it and all my targets are correct. So, what is the problem?

How to catch $broadcast in spyOn?

I don't know why my testing is not working.

it('should be called when "get-tentative-events" is fired', function() {
  spyOn(this.VM, 'addEvents');
  spyOn(this.VM, 'setEventData').and.returnValue(null);

  this.VM.$root.$broadcast('get-tentative-events', []);
  expect(this.VM.addEvents).toBeDefined();
  expect(this.VM.addEvents).toHaveBeenCalled();
});

In debugging, I confirmed addEvents is called.
But there was a error single-calendar addEvents should be called when "get-tentative-events" is fired FAILED

FYI:

if I change

this.VM.$root.$broadcast('get-tentative-events', []);

to

this.VM.addEvents([])

I can pass this test.So I can not understand why my test is failing.

vendredi 29 avril 2016

Some times if I run my tests the lib files are gone from my Output folder, Can someone tell me the reason?

If I run or debug test, this test working but I can't run my main project because lib file not found. If rebuild solution it works.

 [TestMethod]
        public void MyTestMethod()
        {
            Assert.AreEqual(2, 2 + 2);

        }

Thanks for help!

Single Karma / Jasmine test runs fine, multiple tests fail

I'm just starting to unit test my app, and have successfully gotten one test suite to run, yeah! I moved on to start testing a second controller, and as soon as the test runner (karma) hits an inject block, the test fails. Comment it out, and the tests pass again. Can't for the life of me figure out what might be going on. Very basic karma config:

http://ift.tt/1O27n0G

The controller looks like:

angular.module('somemodule')
  .controller('SomeCtrl', SomeCtrl);

function SomeCtrl($rootScope, Notification) {
  $rootScope.$on('someapp.apiLimitExceeded', (evt, err) => {
    Notification.error({
      message: err.data.message
    });
  });
}

The first test looks like:

describe('SomeCtrl', () => {
  let $rootScope, controller, notification;

  beforeEach(() => {
    module('mymodule');

    inject(($injector) => {
      $rootScope = $injector.get('$rootScope');
      notification = $injector.get('Notification');

      spyOn(notification, 'error');

      controller = $injector.get('$controller')('SomeCtrl', {
        $rootScope: $rootScope,
        Notification: notification 
      });
    });
  });

  describe('Initialization', () => {
    it('Should register a $rootScope listener for mymodule.apiLimitExceeded', () => {
      const args = {data: {message: 'dis an errr'}};
      $rootScope.$emit('mymodule.apiLimitExceeded', args);

      expect(notification.error).toHaveBeenCalled();
      expect(notification.error).toHaveBeenCalledWith(args.data);
      expect(notification.error.calls.count()).toBe(1);
    });
  });
});

This test passes, as expected. If I literally copy and paste the contents of this file into another test file, without changing anything, the tests start failing. Removing the second test file makes the original test start passing. I must be missing something about how karma is running these angular tests, or some tearDown I'm not performing, but I can't see what that might be. Any ideas? The error I get, for reference is:

TypeError: Cannot read property '1' of null
at Function.fb.$$annotate (/Users/greg/projects/someapp/client/build/js/deps.js:7451:410)
at Function.angular.injector.$$annotate (/Users/greg/projects/someapp/client/node_modules/angular-mocks/angular-mocks.js:2615:36)
at e (/Users/greg/projects/someapp/client/build/js/deps.js:7298:368)
at Object.invoke (/Users/greg/projects/someapp/client/build/js/deps.js:7299:86)
at Object.workFn (/Users/greg/projects/someapp/client/node_modules/angular-mocks/angular-mocks.js:2965:20)
at window.inject.angular.mock.inject (/Users/greg/projects/someapp/client/node_modules/angular-mocks/angular-mocks.js:2934:42)
at Object.beforeEach (/Users/greg/projects/someapp/client/test/test.again.someapp.controller.js:7:5)
Error: Declaration Location
at window.inject.angular.mock.inject (/Users/greg/projects/someapp/client/node_modules/angular-mocks/angular-mocks.js:2927:25)
at Object.beforeEach (/Users/greg/projects/someapp/client/test/test.again.someapp.controller.js:7:5)
TypeError: Cannot read property '$emit' of undefined
at Object.it (/Users/greg/projects/someapp/client/test/test.again.someapp.controller.js:23:17)

Mocking JDBC's Connection#prepareStatement always returns null with jMockit

I am trying to test JDBC calls to Oracle DB with jMockit. I have tried to simulate JDBC's Connection#prepareStatement(String sql) to return PreparedStatement mock object, but I only get a null value instead. My aim is to mock Connection APIs to return a mock PreparedStatement object, and to mock PreparedStatement APIs to return a mock ResultSet object. Any advice would be gratefully appreciated.

My source code is given below.

try (Connection conn = DriverManager.getConnection(url, username, password);) {
  try(PreparedStatement ps = conn.prepareStatement(
         "SELECT firstName, lastName from Employee where empId = ?");) {
    ps.setString(1, empId); // This is an input to function.
    try(ResultSet rs = ps.executeQuery();) {
      while(rs.next()) {
        Employee emp = new Employee();
        emp.setFirstName(rs.getString("firstName"));
        emp.setLastName(rs.getString("lastName"));
        return emp;
      }
    }
  }
}
return employees;

When I invoke

PreparedStatement ps = conn.prepareStatement(
             "SELECT firstName, lastName from Employee where empId = ?")

My unit test is as follows

@Test()
  public void testQueryOutOfDateSpanishContent_Success(
      @Mocked final Connection connection, @Mocked final PreparedStatement ps) throws Exception {
    new Expectations(DriverManager.class) {
      {
        DriverManager.getConnection(
            dcrParameters.getEnvironmentUrl(), dcrParameters.getUsername(),
            dcrParameters.getPassword());
        result = connection;

        connection.prepareStatement(anyString);
        result = with(new Delegate<PreparedStatement>() {
          public PreparedStatement prepareStatement(String sql) throws SQLException {
            return ps;
          }
        });
      }
    };
    // Call the source function here.

I am using TestNG 6.10 with latest version of jMockit release. I am running the unit test with TestNG eclipse plugin. I am passing -javaagent:C:\downloads\jmockit.jaras a VM argument in Eclipse.

Thanks!!

moq generic method setup on interface

How to setup generic method using moq library in C#

Interface IA
{
    void foo();
    void Get<T>();
}

[Fact]
public void SetupGenericMethod()
{
    var mock = new Mock<IA>();
    mock.Setup(x=> x.Get<It.IsAny<???>()>()
}

Any help on this one is really appreciated. Thanks a bunch for your time

How to simulate no connection in a mocha test

I am just wondering if there is a way to simulate a "no connection" event in a mocha unit test. I have a method that return a promise that should wait for an internet connection with a polling strategy and I want to test it out with mocha. There is a method to achieve such a result.

Some code:

it('should wait for connection', function(done)
{
   this.timeout(2500);

   //simulate an internet connection drop here

   my_object.wait.connection().then(done);
   setTimeout(//activate connection, 2000);
});

Thank you for any response.

How to setup PowerMock for Android instrumentation tests (ART)

I want to use PowerMock in my instrumentations tests but I run into several problems.

I first tried to include de dependencies in the build.gradle

androidTestCompile ("org.powermock:powermock-api-mockito:$POWERMOCK_VERSION") {
    exclude module: 'hamcrest-core'
}
androidTestCompile "com.crittercism.dexmaker:dexmaker:$DEXMAKER_VERSION"
androidTestCompile "com.crittercism.dexmaker:dexmaker-dx:$DEXMAKER_VERSION"
androidTestCompile ("com.crittercism.dexmaker:dexmaker-mockito:$DEXMAKER_VERSION") {exclude group: 'junit' exclude group: 'org.hamcrest', module: 'hamcrest-core' }

And I got the following error:

> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK mockito-extensions/org.mockito.plugins.MockMaker
    File1: /Users/nzylber1/.gradle/caches/modules-2/files-2.1/org.powermock/powermock-api-mockito/1.6.4/fe12509b7e9e49d25131f4155145748a31e42e40/powermock-api-mockito-1.6.4.jar
    File2: /Users/nzylber1/.gradle/caches/modules-2/files-2.1/com.crittercism.dexmaker/dexmaker-mockito/1.4/70892a94894462c1b35df3c8a77d21b7e843550b/dexmaker-mockito-1.4.jar

A google search led me to this post where the accepted answer doesn't provide a solution but mentions PowerMock can't work with Dalvik. But since recent devices and emulators run on ART, it doesn't seem relevant anymore. So I tried the method proposed in the second and unaccepted answer, which was to exclude manually the duplicate files from the PowerMock jar

AGPBI: {"kind":"error","text":"Error converting bytecode to dex:
Cause: java.lang.RuntimeException: Exception parsing classes","sources":[{}],"original":"UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Exception parsing classes
com.android.dx.command.dexer.Main.processClass(Main.java:752)
com.android.dx.command.dexer.Main.processFileBytes(Main.java:718)
com.android.dx.command.dexer.Main.access$1200(Main.java:85)
com.android.dx.command.dexer.Main$FileBytesConsumer.processFileBytes(Main.java:1645)
com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
com.android.dx.command.dexer.Main.processOne(Main.java:672)
com.android.dx.command.dexer.Main.processAllFiles(Main.java:574)
com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
 com.android.dx.command.dexer.Main.run(Main.java:277)
com.android.dx.command.dexer.Main.main(Main.java:245)
 com.android.dx.command.Main.main(Main.java:106)
Caused by: com.android.dx.cf.iface.ParseException: bad class file magic (00051607) or version (0000.0002)
com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:472)
com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
com.android.dx.command.dexer.Main.parseClass(Main.java:764)
com.android.dx.command.dexer.Main.access$1500(Main.java:85)
com.android.dx.command.dexer.Main$ClassParserTask.call(Main.java:1684)
com.android.dx.command.dexer.Main.processClass(Main.java:749)
... 12 more\n","tool":"Dex"}

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebugAndroidTest'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

where the most important line seems to be:

Caused by: com.android.dx.cf.iface.ParseException: bad class file magic 

Again, some research led me to this other post suggesting that the problem is related to incompatibility in java version. My project's compilation target is 1.8 because I'm using retrolambda, si setting it back to 1.7 is not an option.

And here I am (stuck). Any idea is warmly welcome!

opensource version of Wallaby JS

I need an opensource version of Wallaby JS which can run QUnit or Jasmine unit testing in text editor like Sublime.

Click here for the example in Wallaby

Angular 2 testing - service won't inject

I'm using angular 2 and jasmine to try and test a couple of services, one service is dependent on the other. I keep getting a provider error for service.

import {Injectable}     from 'angular2/core';

@Injectable()
export class ServiceA {

constructor() {
}
}

spec for serviceA

import {it, 
describe, expect, 
beforeEach, 
beforeEachProviders, inject}
from 'angular2/testing';
import {ServiceA} from './serviceA;

describe('ServiceA Tests', () => {
let service: ServiceA;

beforeEachProviders(() => {
    return [
        ServiceA
    ]
});
beforeEach(inject([ServiceA], (l) => {
    service = l;
}));

it('Service Created', () => {
    expect(service).toBeDefined();
});

});

config class

import {OpaqueToken} from 'angular2/core';

export let APP_CONFIG = new OpaqueToken('app.config');

export interface Config {
applicationBaseUrl: string;    
}

export const CONFIG: Config = {
applicationBaseUrl: 'some value',
};

service b

import { Injectable,Inject}     from 'angular2/core';
import { Http,Response,RequestOptions,Headers} from 'angular2/http';
import {APP_CONFIG, Config,CONFIG}    from './app.config';
import {ServiceA} from './serviceA';

export interface IServiceB {
}

@Injectable()
export class ServiceB implements IServiceB {

constructor(private _http: Http,@Inject(APP_CONFIG)
private _config:Config,private serviceA: ServiceA) {

}

}

spec for service B

import {it, describe, expect, beforeEach, beforeEachProviders,
inject} from 'angular2/testing';
import {ServiceB} from './serviceB';
import {ServiceA} from './serviceA';
import {HTTP_PROVIDERS, Http, Response, RequestOptions,
Headers}   from 'angular2/http';
import {APP_CONFIG, Config, CONFIG}    from './app.config';
import {provide} from 'angular2/core';

import 'rxjs/Rx'; // Add all operators to Observable

describe('ServiceB Tests', () => {
let serviceB: ServiceB;
let appConfig: Config;
let http: Http;
let serviceA: ServiceA;
beforeEachProviders(() => {
    return [
        HTTP_PROVIDERS,
        provide(APP_CONFIG, { useValue: CONFIG }),
        ServiceA,
        ServiceB
    ]
});
beforeEach(inject([APP_CONFIG, Http, ServiceA,ServiceB], (ac, h, a,b) => {
    appConfig = ac;
    http = h;
    serviceA = a;
    service = b; // new ServiceB(http, appConfig, serviceA);
    appConfig.applicationBaseUrl = '/';

    }));

it('Http created', () => {
    expect(http).toBeDefined();
});

it('service a created', () => {
    expect(serviceA).toBeDefined();
});

it('App config created', () => {
    expect(appConfig).toBeDefined();
});

it('service B created', () => {
    expect(serviceB).toBeDefined();
});


});

Service A loads and runs fine. If I manually create ServiceB things work but if I try to inject ServiceB I get error.

Failed: No provider for ServiceA! (ServiceB-> ServiceA)

It creates ServiceA so not sure why its saying no provider.

How do I complete this Python Tennis Kata?

I'm trying to write the Tennis Kata in python. I've written the code for a standard game, but somehow cannot figure out how to write the Deuce part. Could someone give me an algorithm or help me complete the program? It would be awesome if we can complete the program by just adding new functions and not removing anything. Thanks!

global player_score
player_score = 0
global comp_score
comp_score = 0


class Tennis:
    global player_score
    global comp_score    

    #def __init__(self):
        #self.player_score 
        #self.comp_score 

    def shot(self, player, comp):
        self.player = player
        self.comp = comp
        global player_score
        player_score+=player
        global comp_score
        comp_score+=comp

        #print player_score
        #print comp_score

    def score(self):
        global player_score
        global comp_score

        if player_score==40 and player_score>comp_score:
            print "Player Wins"

        elif comp_score==40 and comp_score>player_score:
            print "Computer Wins"

        elif player_score==40 and comp_score==40: #Deuce part

            pass







game = Tennis()
#game.shot(15,15)
game.shot(15,15)
game.shot(0,10)
game.shot(0,0)
#game.shot(10,0)
#game.shot(0,10)

game.score()


print player_score
print comp_score

MSTEST test results don't show up using Test Explorer

Environment is:

Visual Studio 2013

Debugging a working Unit Test

enter image description here

Test runs fine, as I see this at bottom of Test Explorer:

TestResults

If I click on output above, I see this:

StandardOutput

The output above created from Trace.WriteLine statement:

TraceWriteLine

If I go to the Solution Folder named Test Results I see this:

enter image description here

But Nothing is in there.

Question:

How do I get a copy of the test results as shown in the output window above?

What hasn't Worked

I created a solution .runsettings file, speicifying just the folder name, nothing showed up...

sbt dependency management issue with hbase-testing-utility

i'm attempting to perform unit testing with scalatest, making use of the hbase testing utility to locally test development code. the setup for hbase testing utility in sbt is the struggle right now. when i compile, i get the following error:

[warn]  module not found: org.apache.hbase#${compat.module};1.2.1
[warn] ==== local: tried
[warn]   /root/.ivy2/local/org.apache.hbase/${compat.module}/1.2.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://ift.tt/1NGfV2j
[warn] ==== Akka Repository: tried
[warn]   http://ift.tt/1r2FS1U
[warn] ==== scala-tools: tried
[warn]   http://ift.tt/1NGfV2l
[warn] ==== cloudera-repos: tried
[warn]   http://ift.tt/1r2FUGR
[warn] ==== Sonatype OSS Snapshots: tried
[warn]   http://ift.tt/1NGfV2n
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.hbase#${compat.module};1.2.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn] 
[warn]  Note: Unresolved dependencies path:
[warn]      org.apache.hbase:${compat.module}:1.2.1
[warn]        +- org.apache.hbase:hbase-testing-util:1.2.1 (/workspace/spark/etl/built.sbt#L30-62)

[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.apache.hbase#${compat.module};1.2.1: not found
[error] Total time: 32 s, completed Apr 29, 2016 9:25:27 AM

my build.sbt file is as follows:

val hbaseVersion = "1.2.1"
val sparkVersion = "1.6.1"
val hadoopVersion = "2.7.1"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-streaming" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-streaming-kafka" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-mllib" % sparkVersion ,
  "org.apache.hbase" % "hbase" % hbaseVersion,
  "org.apache.hbase" % "hbase-server" % hbaseVersion,
  "org.apache.hbase" % "hbase-server" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-client" % hbaseVersion,
  "org.apache.hbase" % "hbase-common" % hbaseVersion,
  "org.apache.hbase" % "hbase-common" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-annotations" % hbaseVersion,
  "org.apache.hbase" % "hbase-testing-util" % hbaseVersion % "test",
  "org.apache.hadoop" % "hadoop-minicluster" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-mapreduce-client-jobclient" % hadoopVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-hdfs" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-hdfs" % hadoopVersion classifier "tests",
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion,
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion,
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-common" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-common" % hadoopVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-annotations" % hadoopVersion,
  "org.scalatest" %% "scalatest" % "2.2.6" % "test" ,
  //"org.scalacheck" %% "scalacheck" % "1.12.5" % "test",
  "com.cloudera.sparkts" % "sparkts" % "0.3.0",
  "com.ecwid.consul" % "consul-api" % "1.1.9",
  "joda-time" % "joda-time" % "2.7"
)

resolvers ++= Seq(
  "Akka Repository" at "http://ift.tt/OxKGcq",
  "scala-tools" at "http://ift.tt/1OUMRhz",
  "cloudera-repos" at "http://ift.tt/1j3vwUC",
  "Sonatype OSS Snapshots" at "http://ift.tt/IdfDNV"
)

Anyone understand why this failure is occurring?

What is the best practice for cleaning data after inserting for a unit test

As the head says, after I inserted some rows (just for testing) to the database in a unit test function, I currently place a query at the end of the function to remove those manually, but I believe that is not the best practice to do. So what is it?

Simple Espresso test "Looped for x iterations over 60sec" error

I actually tried to setup some unit test with Espresso and after some hours of research the app do only the click and get focus by the EditText but after that there is nothing

Caused by: android.support.test.espresso.AppNotIdleException: Looped for 1996 iterations over 60 SECONDS. The following Idle Conditions failed .

i've removed all animation & SwipeRefreshLayout cause i saw there is a bug with the swiperefresh

I actually use some callback for replace the current fragment in the Activity

if someone have some tips i'm out after 4 hours of searching u_u

Thanks you :)


My Gradle dependencies :

// App dependencies
compile 'com.android.support:support-annotations:23.3.0'
compile 'com.google.guava:guava:18.0'
// Testing-only dependencies
// Force usage of support annotations in the test app, since it is internally used by the runner module.
androidTestCompile 'com.android.support:support-annotations:23.3.0'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'

I've added this on the defaultConfig :

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

There is my test :

@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {

    public static final String USERNAME = "do_f";

    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule(LoginActivity.class);

    private LoginActivity mActivity = null;

    @Before
    public void setActivity() {
        mActivity = mActivityRule.getActivity();
    }

    @Test
    public void login_LoginActivity() {

        onView(withId(R.id.menu_login)).perform(click());

        onView(withId(R.id.login_username))
                .perform(typeText(USERNAME), closeSoftKeyboard());
    }
}

There is my activity :

public class LoginActivity extends AppCompatActivity
        implements MenuFragment.OnFragmentInteractionListener {

    private FragmentManager fm;

    public static void newActivity(Activity activity)
    {
        Intent i = new Intent(activity, LoginActivity.class);
        activity.startActivity(i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SharedPreferences sp = getSharedPreferences(Utils.SP, Context.MODE_PRIVATE);

        if (!sp.getString(Utils.TOKEN, "null").equals("null"))
        {
            MainActivity.newActivity(this);
            finish();
        }

        fm = getFragmentManager();
        fm.beginTransaction()
                .replace(R.id.container, MenuFragment.newInstance())
                .addToBackStack(null)
                .commit();
    }

    @Override
    public void onBackPressed()
    {
        if (getFragmentManager().getBackStackEntryCount() > 1)
            getFragmentManager().popBackStack();
        else
            super.onBackPressed();
    }

    @Override
    public void showLogin() {
        fm.beginTransaction()
                .replace(R.id.container, LoginFragment.newInstance())
                .addToBackStack(null)
                .commit();
    }

    @Override
    public void showRegister() {
        fm.beginTransaction()
                .replace(R.id.container, RegisterFragment.newInstance())
                .addToBackStack(null)
                .commit();
    }
}

And my LoginFragment :

    private static final String        TAG = "LoginFragment";

@Bind(R.id.loading_spinner)
ProgressBar loading;

@Bind(R.id.content)
LinearLayout content;

@Bind(R.id.login_username)
EditText        username;

@Bind(R.id.login_password)
EditText        password;

public LoginFragment() {

}

public static LoginFragment newInstance() {
    return new LoginFragment();
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.login_fragment_login, container, false);
    ButterKnife.bind(this, v);
    return v;
}

@Override
public void onActivityCreated(Bundle saveInstanceState) {
    super.onActivityCreated(saveInstanceState);
}

@OnClick(R.id.login_submit)
public void onSubmit(View v)
{
    if (username.getText().length() == 0
            || password.getText().length() == 0)
    {
        Snackbar.make(getView(), "blabla", Snackbar.LENGTH_SHORT).show();
        return ;
    }
    //hideContent();
    LoginPost p = new LoginPost(username.getText().toString(), password.getText().toString());
    Call<LoginResponse> call = RestClient.get().login(p);
    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            if (response.body() == null) {
                String msg = getResources().getString(R.string.login_error_bad_credentials);
                Snackbar.make(getView(), msg, Snackbar.LENGTH_SHORT).show();
                //showContent();
            } else {
                SharedPreferences sp = getActivity().getSharedPreferences(Utils.SP, Context.MODE_PRIVATE);
                sp.edit().putString(Utils.TOKEN, response.body().getToken()).apply();
                sp.edit().putString(Utils.USERNAME, username.getText().toString()).apply();
                MainActivity.newActivity(getActivity());
                getActivity().finish();
            }
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Snackbar.make(getView(), "onFailure", Snackbar.LENGTH_SHORT).show();
            //showContent();
        }
    });
}

How to unit test a Slim controller

I have a controller for Slim like this. How would you unit test it? Or shouldn't I unit test controllers?

class Products
{
    protected $ci;
    public function __construct(Container $ci)
    {
        $this->ci = $ci;
    }

    public function get($request, $response)
    {
        try {
            $sku = $request->getAttribute('id');
            $product = $this->ci->get('productModel');
             return $response->withJson($product->get(Auth::$ACCOUNTID, $sku));
         } catch (NotFoundException $e) {
            return $response->withJson(["message" => $e->getMessage()], 404);
         }
    }
}

Code First SQL Express DB from Database First model for Unit testing

I have a database first data model, which I would like use to create an empty code first database to fill it with test data for unit testing purposes. How do I do that? When I'm trying to create a database, I get an 'UnintentionalCodeFirstException'.

My connection string looks like this:

 <add name="MyDBEntities" 
 connectionString="metadata=http://res*/DataModel.csdl|res*/DataModel.ssdl|res*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\v11.0;initial catalog=MyDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Execute test on remote machine using VS2010 Professional

I want to execute my test on a remote machine. I have already setup Test Controller and test agent on my Controller system and test system. But I am unable to find 'Roles' tab under Test settings to configure these tests to run on Remote machine. I read about Missing 'Roles tab' here

My ask is, is there a WAR to this?

I cannot change VS2010 Version.

Mocking pyodbc module calls for django unit tests

I want to make unit tests for some django views which use a custom pyodbc database connection

views.py

from django.http import JsonResponse, HttpResponseNotFound, HttpResponseBadRequest, HttpResponseServerError, HttpResponseForbidden
from django.core.exceptions import SuspiciousOperation
from django.utils.datastructures import MultiValueDictKeyError
import os
import pyodbc

# Create your views here.

db_credentials = os.environ.get('DATABASE_CREDENTIALS')
dbh = pyodbc.connect(db_credentials)

def get_domains(request):
    if request.method == 'GET':
        args = request.GET
    elif request.method == 'POST':
        args = request.POST

    try:
        cursor = dbh.cursor()
        if 'owner' in args:
            owner = args['owner']
            cursor.execute('{call GET_DOMAINS_FOR_OWNER(?)}', owner)
        else:
            cursor.execute('{call GET_DOMAINS()}')
        result = cursor.fetchall()
        if(result):
            return JsonResponse([row[0] for row in result], safe=False)
        else:
            return JsonResponse([], safe=False)
    except pyodbc.Error as e:
        return HttpResponseServerError(e)
    except SuspiciousOperation as e:
        return HttpResponseForbidden(e)

Since I don't want the unit tests to be hitting the database, how can I mock the behaviour given that:

  • The mock library won't work since pyodbc is a Python C extension
  • Using sys.modules doesn't seem to work, probably because the module is being used in views.py and not on tests.py

Here is my test driver

tests.py

from django.test import SimpleTestCase
from sms_admin import *

# Create your tests here.


HTTP_OK = 200
HTTP_NOTFOUND = 404


class AdminTestCase(SimpleTestCase):
    """docstring for AdminTestCase"""

    def test_get_pool_for_lds(self):
        response = self.client.get('/sms_admin/get_pool_for_lds', {'domain': 'sqlconnect', 'stage': 'dev', 'lds': 'reader'})
        self.assertEqual(response.content, b'pdss_reader')
        self.assertEqual(response.status_code, HTTP_OK)

run MATLAB unit tests in parallel

In this framework

http://ift.tt/1SP5qch

I found MATLAB could run test cases from the same matlab.unittest.TestCase in parallel by

run(MyTest); 

If MyTest is hierited from matlab.unittest.TestCase.

How to run multiple matlab.unittest.TestCase classes in parallel? Thank you,

Moq callbase for async methods don't work

I have class which is mocked but in some cases I need to run original method

public virtual async Task<int> SaveChangesAsync(string userId)
{
    try
    {
        TrackChanges(userId);//sets some fields
        return await db.SaveChangesAsync();
    }
    catch (Exception e)
    {
        LogSaveValidationFailed(e);
        throw;
    }
}

I have tried CallBase = true, but it don't work for async methods, also tried workaround with CallBack...

var db = new Mock<DbContext>();
db.CallBase = true;
db.Setup(x => x.SaveChangesAsync(It.IsAny<string>())).ReturnsAsync(1).Callback((string user) =>
{
    db.Object.SaveChanges(user);
});

...it returns value bud never call callback. Everything works normal method but doesn't work with async. What can I do to make it work with Moq, or it's better just refactor a bit and move TrackChanges from async method to normal?

How do I setup a unit test user for django app? The unit test can't login

I've enabled login authentication for my django app. Unit tests for views are not working because they get stuck at the login page. Setting a breakpoint immediately after the view's response is returned and using

print response.content

results in output that contains the phrase 'please login'

How do I setup a user so the testcase can login? I've tried using my username and password, but it doesn't work in the unit test context.

How do I fetch-mock a post request with a payload

I am using the wheresrhys fetch-mock npm module to run functional testing in my app. I would like to mock a fetch with method 'POST' and a specific payload.

It would look something like this:

fetchMock.mock({
        routes: {
            name: 'LoginSuccess',
            matcher: "https://myurl",
            method: 'POST',
            payload: {
                params:{User: "ABCDE@gmail.com", Password: "password"}
            },
            response: {  
                result:{
                    message: "Successful login", 
                    credentials: "XXXXXXXXXXXXX"
                }
            }
        }
    });

I would like to check the payload of my fetch and give a response correspondingly. For example I could simulate one login where the user submits the wrong password, then they try again and submit the correct info and are granted access. Same url, different payloads, different responses.

Is it possible to do this? I know it's possible to check the method of the fetch, but I'd like to do the same with payload.

Or is there a better way to do this?

I haven't found a solution in the readme of the module or in the test section of the fetch-mock package.

Thanks for any tips or suggestions!!

*also I would have liked to tag this with fetch-mock but the tag doesn't exist!

Coverage report with istambul and mocha

I'm a newbie on Node.js, I have to setup some test in my application and I'm getting really mad on trying to generate a back-end coverage report with mocha and istambul in my loopback application.

Searching through thousand of dab explained articles on Github I found some good articles and then I figured that I had to use something like this:

istanbul cover _mocha -- [path/to/test/files] -R spec

I was happy because it says: "What you are essentially doing is passing the command to run your tests to Istanbul which in turn, will run those tests on your behalf." but every time I try to run this I got this error:

No coverage information was collected, exit without writing coverage information
C:\...\proj-name\node_modules\.bin\_mocha:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list

My working test file is:

var userService = require('../TestBusinessLogic.js');
var should = require('chai').should();

describe('API Utenti', function() {
  it('should throw Exception on missing UserName', function() {
    (function() {
      userService({ Name: 'Pippo', Surname: 'Baudo' });
    }).should.Throw(Error);
  });
});

Is this command good to use? If not, could someone please explain me how to make a coverage report using istambul with mocha?

Testing properties with private setters

Currently in a part of my project a domain object like below exists:

public class Address
{
    public virtual string HouseName { get; set; }

    public virtual string HouseNumber { get; set; }

    public virtual string RoadName { get; set; }

    public virtual string Postcode { get; set; }

    public virtual string District { get; private set; }
}

The District property is a calculated column in the database. Due to the requirements of the data access provider (Entity Framework) a private set is required. This is fine in normal program flow as the District never needs to be set, due to it being updated when an Address record is saved/updated in the database

A method that I want to test looks like this:

public IEnumerable<House> GetHousesWithinSameDistrict (int addressId)
{
    var addressToMatch = _addressRepository
      .FirstOrDefault(address => address.Id == addressId)

    return _houseRepository
      .Where(house => house.Address.District == addressToMatch.District)
}

This is causing me problems when I try to set up the addressToMatch variable, as I am unable to set the District property and as such I cannot write a test to check correct matching addresses are returned.

How should I go about setting up an Address object for this test?

Failed in some cases - javascirpt

I got the following challenge in interview, with some constraints.

Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, such that, A1+A2...A(i−1)=A(i+1)+A(i+2)...AN.

Input Format

The first line contains T, the number of test cases. For each test case, the first line contains N, the number of elements in the array A. The second line for each test case contains N space-separated integers, denoting the array A.

Output Format

For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.

Constraints

1≤T≤10

1≤N≤10^5

1≤Ai≤2×10^4

1≤i≤N

I have solved it but it's failing in some test cases, i have spend almost 4-5 hr but unable to solve it. My solution is

function processData(input) {
    input = input.split('\n');
    var counter=0;
    var sum = function(n){
        var r=[];
        for(var k=0;k<n.length;k++){
            if(!isNaN(n[k])) {
                if(n[k] >= 1 && n[k] <= (2 * Math.pow(10,4))){
                    r.push(n[k].trim());
                }
            } 
        }
        return r.reduce(function(a, b) { return Number(a) + Number(b); }, 0);
    }
    for(var i=2;i<=input.length;i+=2){
        var ret='NO';
        if(counter<=10){
            input[i] = input[i].split(' ');
            if(input[i].length <= Math.pow(10,5) &&   input[i-1] <= input[i].length && input[i-1] >= 1){
                for(var j=0;j<input[i].length;j++){
                    if(sum(input[i].slice(0,j)) ===  sum(input[i].slice(j+1,input[i].length))){
                        ret = 'YES';
                        break;
                    }
                }
            }
        }
        counter++;
        console.log(ret);
    };

} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

How to use JUnit and Mockito to mock inner logic

I'm king of new to Junit and Mockito and trying to understand how to mock parts of logic of a class.

I have a method which does a http post and get call, but it might be a DB lookup. How do I mock the response from the HTTP call in this method

  BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

I mean there must a way to test my logic without doing to real http call or db lookup or whatever.

// HTTP GET request
public String sendGet(URL url) throws Exception {

    s_logger.debug("URL: " + url);
    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

    // Add request header
    httpsConnection.setRequestMethod("GET");
    httpsConnection.setRequestProperty("Content-Type", "application/xml");

    if (sessionId != null) {
        httpsConnection.setRequestProperty("sessionId", sessionId);
    } else {
        httpsConnection.setRequestProperty("username", ACCOUNT_USERNAME);
        httpsConnection.setRequestProperty("password", ACCOUNT_PASSWORD);
    }

    httpsConnection.setInstanceFollowRedirects(false);
    httpsConnection.setUseCaches(false);

    // Print Request Header
    s_logger.debug("Request Header: " + httpsConnection.getRequestProperties());

    int responseCode = httpsConnection.getResponseCode();
    s_logger.debug("Response Code : " + responseCode);

    Map<String, List<String>> headerFields = httpsConnection.getHeaderFields();
    s_logger.debug("Response Header: " + headerFields);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // Set Session ID
    final String SESSION_KEY = "sessionId";
    if (this.sessionId == null && httpsConnection.getHeaderFields().containsKey(SESSION_KEY)) {
        this.sessionId = httpsConnection.getHeaderFields().get(SESSION_KEY).get(0);
        s_logger.debug("SESSION ID : " + this.sessionId);
    }

    // print result
    s_logger.debug("RESPONSE: " + response.toString());
    return response.toString();
}

Thanks for any help or suggestion.

Stub a function which is inside the function to be tested

I have a function let's say A whose output and functionality I have to test, A calls another function B which takes a lot of time to compute the output. So I am trying to use stubs to mimic all the values that B returns.

def A
  #do something
  output = B
  #do something with output
end

Now the test files

describe "check what A returns" do
   ClassName.stub(:B) do
     [0, 1]
   end
   test_values  = TestClass.A(input parameters)
   #checks on test values
end

My aim is to pass the expected output of B to function A. I am using RSpec. How do I go about it?

How to use a function defined in service in another controller in angularjs unit test

I have a function called 'functionA' in service called ServiceA maybe:

return Restangular
    .extendModel('modelA', function(model) {
            model.functionA = function(body) {
                return this.customPUT(body, 'add')
            };
            return model;
    })
    .service('accounts');

And I can use it in ControllerB, it works well.

function functionB(body){
    instanceModelB.instanceModelA.functionA(body)
            .then(onSuccess)
            .catch(onFail)
            .finally(onFinally);
}

But How to use it in the unit test for ControllerB? I mean how to call functionA in unit test for ControllerB? It always says 'functionA is not a function'. Thanks in advance.

AndroidStudio 2.0 runs unit tests as instrumentation tests

AndroidStudio 2.0 runs unit tests as instrumentation tests. I've disabled an "Enable all test artifacts.." option and set the artifact to unit tests. However, AS still tries to run an emulator and it doesn't see any unit tests at all. Any ideas?

Way to write Validation tests for Login screen in CODEDUI

Being a bignner in CodedUI i have small query suppose we write some UI tests for "Login" Screen in UIMap class like below

public void IsValidUser()
        {
            //Define sample app Main window
            WpfWindow mainWindow = new WpfWindow();
            mainWindow.SearchProperties.Add(WpfWindow.PropertyNames.Name, "ValidatingControlsView");
            mainWindow.SearchProperties.Add(WpfWindow.PropertyNames.ControlType, "Window");
            mainWindow.WindowTitles.Add("ValidatingControlsView");

            //Username text box
            WpfEdit txtusrname = new WpfEdit(mainWindow);
            txtusrname.SearchProperties.Add(WpfButton.PropertyNames.AutomationId, "txtUsername");
            txtusrname.WindowTitles.Add("ValidatingControlsView");
            Keyboard.SendKeys(txtusrname, "XXXXX");

            //Passsowrd Textbox
            WpfEdit txtpasword = new WpfEdit(mainWindow);
            txtpasword.SearchProperties.Add(WpfButton.PropertyNames.AutomationId, "txtpassword");
            txtpasword.WindowTitles.Add("ValidatingControlsView");
            txtpasword.Text = "XXXXX";

            //Login button Click
            WpfButton blogin = new WpfButton(mainWindow);
            blogin.SearchProperties.Add(WpfButton.PropertyNames.AutomationId, "btnLogin");
            Playback.Wait(1000);
            Mouse.Click(blogin);}

Now Suppose i want to check all validation checks i.e both Positive ad negative what is best way to write them .i have tried below but i dont know it is the best way or not.

//validation checks
            string expectedUsername = "XXXX";
            string expectedPassword = "XXXXX";
            if (!string.IsNullOrEmpty(txtusrname.ToString()) && !string.IsNullOrEmpty(txtpasword.ToString()))
            {
                if (txtusrname.ToString() == expectedUsername && txtpasword.ToString() == expectedPassword)
                {
                    Assert.IsTrue(true, "Message.");
                }
                else { Assert.IsFalse(false, "Message"); }
            }
            else
            {
                Assert.IsFalse(false, "Message.");
            }

How to mock a service making use of $resource from within a controller?

In my controller I am making use of a service that itself uses $resource. The result of calling the service method can be either a success or error callback. My question is what is the best way to to mock these responses so I can test that the necessary stuff in my controller?

My controller:

(function() {

  angular
    .module('myApp')
    .controller('widgetCtrl', widgetCtrl);

  widgetCtrl.$inject = [
    'dataService'
  ];

  function widgetCtrl(dataService) {
    var vm = this;
    vm.setAViewModelValue = setAViewModelValue;
    vm.getWidgets = getWidgets;

    function setAViewModelValue() {
      vm.blah = 'This is a simple thing to test';
    }

    function getWidgets() {
      dataService.widgets().query(function(response) {
          vm.widgets = response;
      },
      function(error) {
        vm.error = error;
      });
    }
  }
})();

My spec file:

describe('Controller: widgetCtrl', function() {

  beforeEach(module('myApp'));

  var widgetCtrl;
  var scope;

  var dataServiceMock = ???;

  beforeEach(inject(function($rootScope, $controller, dataService) {
    scope = $rootScope.$new();
    scope.vm = {};
    ScheduledReportCtrl = $controller('widgetCtrl as vm', {
      $scope: scope,
      dataService: dataServiceMock
    });
  }));

  describe('setAViewModelValue()', function() {
    it('sets a view model value', function() {
      scope.vm.setAViewModelValue();
      expect(scope.vm.blah).toEqual('This is a simple thing to test');
    });
  });

  describe('getWidgets()', function() {
    it('sets vm.widgets if successful', function() {
      ???
    });

    it('sets vm.error if not successful', function() {
      ???
    });
  });
});

Test Observable subscriber behaviour

I'm writing a test to check the behaviour of my subscriber. I have a method like that:

public void myMethod(){
     myObservable.subscribe(result -> {
         count++;
     })

}

I want to test that myMethod increments count variable when result is emmited, but because count is incremented asynchronously, I need to wait until result is emmited to check count status. How can I do that?

PHPunit Bug Mock assert Binary String

i have found weird result about phpunit Mock

I ask myself if this bug is cause by UTF8 char in serialize()

When serialize object with private or protected the mock return something like this

Expectation failed for method name is equal to <string:error> when invoked zero or more times
Parameter 0 for invocation Bar::error(Binary String: 0x4f3a333a22466...b4e3b7d) does not match expected value.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'O:6:"Foo":1:{s:5:"title";N;}'
+Binary String: 0x4f3a333a22466f6f223a313a7b733a32303a22002a00666f6f50726f74656374656456616c7565223b4e3b7d

Code

class Foo
{
    public $fooPublicValue;
    protected $fooProtectedValue; //BREAK
    private $fooPrivateValue;     //BREAK
}

class Bar
{
    public function error($message)
    {
        //some process
    }
}

class Baz
{
    public function exec(Bar $bar)
    {
        $bar->error(serialize(new Foo()));
    }
}

class BazTest extends \PHPUnit_Framework_TestCase
{
    public function testExec()
    {
        $loggerMock = $this->getMockBuilder('Bar')
            ->getMock();

        $loggerMock
            ->method('error')
            ->with($this->equalTo('O:6:"Foo":1:{s:5:"title";N;}'));

        (new Baz())->exec($loggerMock);
    }
}

Manage angularjs controller init with karma tests

Ive seen such questions and they all say 'extract logic out into a service and mock the service'. Simple, except i have as much as possible.

So when the controller inits i have a call to $scope.getWidgets() this method calls widgetService to get a list of widgets for the user, it will then display a toast notification using notifyService. Should widgetService reject its promise or the user have no widgets a call to notifyService is made. This is all done when the controller inits.

$scope.getWidgets = function () {
    widgetService.getWidgets()
        .then(function (widgets) {
            if (widgets.length === 0) {
                notifyService.notify('no widgets');
            }

            $scope.widgets = widgets;
        })
        .catch(function (e) {
            notifyService.notify('oh noes');
        });
}

//called at bottom of controller
$scope.getWidgets();

Now all my tests so for have not had need to run any digest cycles, run running promises etc. The method im trying to test calls a service to save a widget. Should it succeed or fail it will again call notifyService to send a notification to the user. I'm testing that the notification is triggered using karma's spyOn and also testing some flags are set correctly. There's no real logic, thats done in the service.

$scope.saveWidget = function (widget) {
    widgetService.saveWidget(widget)
        .then(function () {
            notifyService.notify('all dandy');
            //set some scope flags, no logic
        })
        .catch(function (e) {
            notifyService.notify('oh noes');
            //set some more scope flags, no logic
        });
}

So now i have have to run the digest cycle to trigger my promises. The Trouble is my mock for widgetService.getWidgets() returns a promise. So when i run the digest first it resolves the promise registered in my init, which calls the notify service, which activates my spyon, concluding my test with false data.

Here are my tests, (please forgive the big code block, ive tried to strip it down as much as possible).

describe('tests', function () {
    var scope, controlelr, _mockWidgetService, _mockNotifyService;

    beforeEach(function () {
        //Init the service mocks, angular.noop for methods etc
        _mockWidgetService = init();
        _mockNotifyService = init();
    });

    beforeEach(function () {
        //Regisetr hooks to pull in my mocked services
        angular.mock.module('myModule');

        angular.mock.module(function($provide) {
            $provide.value('widgetService', _mockWidgetService);
            $provide.value('notifyService', _mockNotifyService);
        })
    });

    angular.mock.inject(function ($controller, $rootScope, widgetService, notifyService) {
        //create scope and inject services to create controller
        scope = $rootScope.$new();

        //Trouble is $scope.getWidgets() is called now.
        controller = $controller('testController', {
            $scope: scope,
            widgetService: widgetService,
            notifyService: notifyService
        });
    });

    describe('getWidgets', function() {
        it('myTest', function () {
            //I cannow manipulate mock services moreso if needed just for this test
            spyOn(_mockNotifyService, 'notfy');

            //Call save widget
            scope.saveWidget();

            scope.$digest();

            expect(_mockNotifyService.notify).toHaveBeenCalledWith(//values);
        });
    });
});

So as you can see im struggling, i could mock all the mocks required for the init code, but id rather only mock the services i need for that test. Plus i don't like the idea of the init code running every single test potentially causing false errors (it has its own tests).

Ive seen $onInit event the controller calls, i had the idea of putting the init call in that but i don't see how i can intercept that to prevent it running for the tests that dont need it. Any advise or solutions to such use cases would greatly appreciated.

jeudi 28 avril 2016

What is unit test and the difference between it and daily normal testing

What is unit test? What are the difference between unit testing and normal testing (say just press F5 of VS to run and see if there is any bugs)?

Mocking a ServletRequest throws exception

To improve my code coverage I mock my methods containing servlet requests and responses, so I create a Unit test with following structure:

public class AccessFilterTest {
    private AccessFilter accessFilter;

    @Mock
    private FilterConfig filterConfig;

    @Mock
    private ServletRequest request;



    @Before
    public void setUp(){
        accessFilter = new AccessFilter();

        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testAccessFilter() throws Exception {
        accessFilter.init(filterConfig);


        accessFilter.destroy();
    }
}

Without the Mock request, this test passes. But when I add the request mock, just as attribute, I get following exception:

java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletInputStream

at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2615) at java.lang.Class.getDeclaredMethods(Class.java:1860) at org.mockito.cglib.core.ReflectUtils.addAllMethods(ReflectUtils.java:349) at org.mockito.cglib.proxy.Enhancer.getMethods(Enhancer.java:427) at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:457) at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217) at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378) at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318) at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:110) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:62) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56) at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23) at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26) at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51) at org.mockito.Mockito.mock(Mockito.java:1243) at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:30) at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16) at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43) at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66) at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71) at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55) at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108) at com.trax.watson.AccessFilterTest.setUp(AccessFilterTest.java:31)

Line 31 is: MockitoAnnotations.initMocks(this);

What is going wrong?

Code coverage with optimization

Currently I have a bunch of unit tests for my C++ project, but I am not (yet) testing the code coverage. I am compiling the tests with -O3 optimization flag to expose potential subtle bugs, but it seems if I want to collect coverage information with tools like gcov, any optimization flag must be disabled. Should I build the tests twice (one with -O3, the other without)? How is this problem usually dealt with?

Mocking a nested objects with sinon

I have a test where I'm trying to test the construction of an api call. I am trying to mock the api and am wondering how to access nested objects with sinon.

it('should create the correct fetch method', (done) => {
    let mock = { shop: {get: (...args) => true } };
    let api = sinon.mock(mock);
    let file = sinon.spy();
    let endpoint = 'shop.get';
    let args = {optionA: 'a', optionB: 'b'};

    api.expects(endpoint).withArgs(...args); // throws error

    fetch.call(api, endpoint, file, ...args)
      .then(() => {
        api.verify();
        done();
      });
  });

I'm getting this type error: TypeError: Attempted to wrap object property shop as function

how to do unit test on tornado

The tornado testing subject doc is so simple, I am not quite sure how to do a unit test on tornado. like that:

here is a api.py:

import tornado
import logging
from tornado.web import RequestHandler
import time


class AnalyticsBWSpecificHour(RequestHandler):
    def get(self):
        return self.write({'message':'no get method'})


class Application(tornado.web.Application):
    def __init__(self,**kwargs):
        api_handlers = [
            (r"/", AnalyticsBWSpecificHour),
        ]

        logging.debug(api_handlers)

        super(Application, self).__init__(api_handlers, **kwargs)

and the test_tornado.py :

from api import Application

from tornado.testing import AsyncHTTPTestCase
import tornado
import logging
logging.basicConfig(level=logging.DEBUG)
import unittest

class ApiTestCase(AsyncHTTPTestCase):
   def get_app(self):
        self.app = Application(debug=True)
        return self.app

    def test_status(self):
        print(self.get_url('/'))
        response = self.fetch(self.get_url('/'),method='GET')
        self.assertEqual(response.code,200)

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

even this is quite simple example, I also get the 599 error. please help me.

RxSwift Unit Testing

I have a simple RxSwift Observable sequence that I am trying to unit test.

    var pass = false
    _ = service!.authenticate().subscribeNext { res in
        XCTAssert(res.tokenValue == "abc123")
        pass = true
    }
    XCTAssertTrue(pass)

This test will fail intermittently as if the subscribeNext block isn't hit. Any ideas on what I'm doing wrong?

Unit Test Finishes before Thread.Sleep time

My program is a simple timer (it's a Pomodoro Timer). I'm trying to incorporate unit testing into my personal projects.

I run my tests on each timer class' run() method and assert that the endTime - startTime is within 1 second of how long I set the timer.

MyTimer.run() invokes Thread.sleep(timerMilliseconds).

My unit tests pass in less time than each timer is set for.

How is this possible?

Eg. Rest is set to 5 seconds, unit test passes in < 1ms

[TestMethod]
        public void testRun () {
            TimeSpan fiveSeconds = new TimeSpan(5000);
            Rest rest = new Rest(fiveSeconds, null);
            TimeSpan now = DateTime.Now.TimeOfDay;
            try {
                rest.run(); //Thread.Sleep(base.getMinutes().Milliseconds);
            }
            catch (Exception e) {
                Assert.Fail(e.ToString());
            }

            Assert.AreEqual(now.Add(fiveSeconds).TotalMilliseconds, DateTime.Now.TimeOfDay.TotalMilliseconds, 1000 , "Actual sleep time not expected");
        }

Test Express Route in Nodejs with mocked Restler

I am very new to NodeJS.I need some help testing a simple API i have build with Express.

I have the following route in my API:

router.get('/execute', function(req, res, next) {
console.log("Execute Request Query: %s", util.inspect(req.query, false, null));

// Validate Reqest. gremlin is Mandatory field 
if (req == null || req.query.gremlin == null) {
    res.status(400).send(getErrorResponse("Invalid Request", "Request is missing mandatory field: gremlin"));
    return;
}

queryDB(req.query.gremlin, res);
});

This Route calls a shared method queryDB which is making an API call to the Titan DB using its Restful Interface. I am using node_module Restler to make this API Call.

function queryDB(query, res) {
console.log("Constructed Gremlin Query: %s. Querying Titan with URL: %s", util.inspect(query, false, null), titanBaseUrl);

rest.postJson(titanBaseUrl,
    { gremlin: query },
    { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }
).on('complete', function(data, response) {
    if (response != null && response.rawEncoded != null && response.statusCode / 100 == 2) {
        console.log("Call successful. Response.rawEncoded: %s", util.inspect(response.rawEncoded, false, null));
        res.send(getResult(response));
    } else {
        console.error("Call failed. Response: %s", util.inspect(response, false, null));
        res.status(500).send(getErrorResponse("Bad Gremlin Response", response));
    }
});
}

Now, I want to test my API's "execute" endpoint. I am able to do this with following:

var www = require("../bin/www");
var superagent = require('superagent');
var expect = require('expect.js');
var proxyquire = require('proxyquire');

describe('server', function() {

before(function() {
    www.boot();
});

describe('Execute', function() {
    it('should respond to GET', function(done) {
        superagent
            .get('http://localhost:' + www.port + "/gremlin/execute?gremlin=99-1")
            .end(function(err, res) {
                expect(res.status).to.equal(200);
                expect(res.body.data[0]).to.equal(98);
                done()
            })
    })
});

after(function() {
    www.shutdown();
});
});

However I am currently making call to my database which I need to mock. I saw some examples online that help you mock node modules that I could use to mock "Restler". However since I am testing an API by calling the endpoint, I am not sure how to mock a module for this.

I looked at the following examples: http://ift.tt/24nt8Bm http://ift.tt/1rlUHNo etc.

Any help or suggestion is appreciated. Thanks.

How to fill an object with data in NUnit

How is it possible to add data to a TestCaseSource object which contains a Dictionary?

I have following code:

static object[] FileInfoCases =
        {
        new object[] { new Dictionary<string, List<BackupFileInfo>>()["source"] = new List<BackupFileInfo>() { .FileName = "", FileLastChanged = new DateTime(), FullPath = "TestPath" } }
        };

BackupFileInfo is my Cutsom object. The values FileName and FileLastChanged and FullPath are Attributes of my custom object. Now I want to fill the List. My custom object is not static. I can not access the attribute names within the list.

Can someone help me please?

Jest Test React Component

I'm trying to test an component that I've created, but I have some problems. I was reading and learning jest. So I install jest-cli on my project

Thats my component:

import React from 'react';
import classNames from "classnames";

let PropTypes = React.PropTypes;

class Pagination extends React.Component {
    constructor(props) {
    super(props);
}

render() {
    let totalPages = [];
    for (let x = 1; x <= this.props.totalPages; x++) {
        totalPages.push(x);
    }
    let pages = totalPages.map(function(page) {
        let attr = {
            href: '',
            onClick: this.props.setCurrentPage.bind(this, page)
        }

        let link = React.DOM.a(attr, page);
        let active = false;
        if (page == this.props.page) {
            let active = true;
            link = React.DOM.span({}, page);
        }
        return React.DOM.li({className: classNames({'active': active})}, link);
    }.bind(this));

    let attrBack = {
        href: '',
        className: 'btn',
        onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) - 1))
    };
    let attrNext = {
        href: '',
        className: 'btn',
        onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) + 1))
    };
    let pagination = React.DOM.div({className: 'pagination'}, 
        React.DOM.ul({}, 
            React.DOM.li({}, React.DOM.a(attrBack, React.DOM.i({className: classNames({'fa fa-chevron-left': (this.props.page != 1)})}))),
            pages,
            React.DOM.li({}, React.DOM.a(attrNext, React.DOM.i({className: classNames({'fa fa-chevron-right': (this.props.page != this.props.totalPages)})})))
        )
    );
    return (pagination);
}
}

Pagination.propTypes = {
   setCurrentPage: PropTypes.func.isRequired,
   page: PropTypes.number.isRequired,
   totalPages: PropTypes.number.isRequired,
}

export default Pagination;

and here my Test

jest.dontMock('../../../components/content/elements/pagination');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Pagination from '../../../components/content/elements/pagination';

describe('Pagination', () => {

    let setCurrentPage = jest.genMockFunction();
    Pagination._setCurrentPage = setCurrentPage;

    it('renders without problems', () => {
        const pagination = TestUtils.renderIntoDocument(
            <Pagination setCurrentPage={() => {}} page={1} totalPages={10} />
        );

        const renderedPagination =     TestUtils.findRenderedDOMComponentWithClass(pagination, 'pagination');

        expect(TestUtils.isDOMComponent(renderedPagination)).toBe(true);
    });
});

but when I exec the test, shows me the error:

Error: Did not find exactly one match (found: 0) for class:pagination

Django-Compressor throws UncompressableFileError on bower installed asset

When I run my unit tests I am getting UncompressableFileError for files installed through Bower. This happens because I don't run bower install in my unit tests and I don't want to have to run bower install for my unit tests.

Is there a way to disable django-compressor, or to mock the files so that this error doesn't happen?

I have COMPRESS_ENABLED set to False but no luck there, it still looks for the file.

XCode 7.3 SDK iOS 9.3, XCTest UI unit tests failing

I have been using XCTest UI unit tests in my app, it worked great with XCode 7.2. with base SDK iOS 9.2, but as soon as I tried to run them with XCode 7.3, with bas SDK iOS 9.3, all of them are failing.

After looking at the issue, it seems that after the app launches, it tries to tap on the buttons a little too fast, note that at this point I can assert for the existance of the button with a simple NSPredicate, and it does in fact exist, the engine finds it, but when it tries the tap, despite not failing in the logs, the method for the IBAction does NOT get called. I created a brand new project to test this issue, first I simply created a single view application, no navigation controller involved, with a single UIButton, and hooked up the IBAction to the view controller, then simply added this UI unit test:

    func testExample()
{
    XCUIApplication().buttons["Button"].tap()
}

And set a breakpoint in the IBAction method on my view controller, it got called. Then I decided to make my view controller with the button the root view controller of a UINavigationController, ran the same test, and now the tap does not work!. If I add a simple delay such as:

    func testExample()
{
    sleep(1)
    XCUIApplication().buttons["Button"].tap()
}

Then the button tap happens, and the executions stops on the IBAction breakpoint, If I run this code without the sleep in XCode 7.2. it also gets called. There seems to be a definite problem with XCode 7.3 or rather iOS Base SDK 9.3, with XCTest UI testing, I know i can simply add sleep at setUp for all test cases, and they work, however this is a big hack, surprisingly I could not find any topics online with this issue, anyone else experiencing the same and has a good work around for it?

Insert function as parameter

Im unit testing my Alamofire code at the moment. Im trying to create a reusable method that I can pass in a status code and a method that will need to be invoked as parameters. I was thinking of using a closing block but the syntax is escaping me and it doesnt help that I have started with Swift. Here is an example:

func parseJsonResponse(response: Response <AnyObject, NSErrror>){
    //parsing
}

func test_networkRequest(withStatusCode statusCode: Int, /* parse function as parameter */) {

      stub(isHost("https://httpbin.org")) { _ in

        return OHHTTPStubsResponse(fileAtPath:OHPathForFile("wsresponse.json", self.dynamicType)!,
            statusCode:statusCode, headers:["Content-Type":"application/json"])
    })

    Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            XCTAsertNotNil(response)


            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }

            //method should go here
            self.parseJsonResponse(response)


    }
}

I want to be able to make 'test_networkRequest' reusable in all my classes, and there will be different types of json to be parsed and handled in various ways. This is why I would like to be able to pass in a function as a parameter into 'test_networkRequest'.

I hope my end goal is clear, and I am open to suggestions if I am off track. :)

PHPUnit Mock RequestStack of symfony

I don't understand how mock this : $requestStack->getCurrentRequest()->getContent()

there are 2 methods : getCurrentRequest()->getContent() and it return a json object (POST Response)

I use symfony with RequestStack class.

The entire code is

class MessageReceivedService
{
    protected $message;

    public function __construct(RequestStack $requestStack)
    {
        $this->message = json_decode($requestStack->getCurrentRequest()->getContent());
    }

    public function getMessage()
    {
        return $this->message;
    }
}

Thank you very much.

The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code

Hey I'm trying to Define a mock database . I'm encountering an error while trying to equate var to Mock<'Repository'> The error is :

The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code.

The Code that I have written is :

 public   class MockingDatabse
{
    //Mock a Payment Info
    var newPayment = new Mock<IPayment>();
}

I know that I can replace 'var' with 'Mock<"Repository">'. But I wanna know I'm not able to use 'var'

Using Castle Windsor in Unit Test Class

I'm a noob with Castle Windsor. I'm building an application that uses Entity Framework 6 and Castle Windsor, with an MSTest Unit Test class. My application has a class in it that implements IWindsorInstaller. My unit test class looks like this:

[TestClass]
public class DatabaseTests {

    static readonly WindsorContainer Container = new WindsorContainer();

    public DatabaseTests() {
        Container.Install( FromAssembly.This() );
    }

    [TestMethod]
    public void FirstTest() {
        // Test statements
    }

    [TestMethod]
    public void SecondTest() {
        // Test statements
    }

    // Other tests
}

There is also an installer class in the unit tests project that looks like this:

public class TestsInstaller : IWindsorInstaller {
    public void Install( IWindsorContainer container, IConfigurationStore store ) {
        container.Install( new RecipeManager.RepositoriesInstaller() );
    }
}

When I go to the Unit Test Session window & try to run all tests, the first one succeeds, and I get this stack trace for the rest:

Unable to create instance of class UnitTests.DatabaseTests. Error: Castle.MicroKernel.ComponentRegistrationException: Component RecipeManager.DAL.CategoryRepository could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.. at Castle.MicroKernel.SubSystems.Naming.DefaultNamingSubSystem.Register(IHandler handler) at Castle.MicroKernel.DefaultKernel.AddCustomComponent(ComponentModel model) at Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) at Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) at RecipeManager.RepositoriesInstaller.Install(IWindsorContainer container, IConfigurationStore store) in C:\Users\Tony\documents\visual studio 2015\Projects\RecipeManager\ManageRecipes\RepositoriesInstaller.cs:line 10 at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope) at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers) at UnitTests.TestsInstaller.Install(IWindsorContainer container, IConfigurationStore store) in C:\Users\Tony\documents\visual studio 2015\Projects\RecipeManager\UnitTests\TestsInstaller.cs:line 8 at Castle.Windsor.Installer.AssemblyInstaller.Install(IWindsorContainer container, IConfigurationStore store) at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope) at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers) at UnitTests.DatabaseTests..ctor() in C:\Users\Tony\documents\visual studio 2015\Projects\RecipeManager\UnitTests\DatabaseTests.cs:line 17

If I run the unit tests one at a time, they all succeed. I intend to build lots of tests, so I'd really rather be able to run them all at once. How do I fix this?

How to assert two list with dicts without order?

everyone. I recently switch from python 2 to 3.5.1 and there was an assert function, which I cannot rewrite.

def assertEqualUnordered(self, data1, data2):
    """
    compare that data are similar
    i.e.:
    [d1, d2] == [d2, d1]
    or
    {'a': [d1, d2]} == {'a': [d2, d1]}
    or
    [{'a': [d1, d2]}, {'b': [d3, d4]}] == [{'b': [d4, d3]}, {'a': [d2, d1]}]
    """
    if isinstance(data1, list) or isinstance(data1, tuple):
        self.assertEqual(len(data1), len(data2))
        for d1, d2 in zip(sorted(data1), sorted(data2)):
            self.assertEqualUnordered(d1, d2)
    elif isinstance(data1, dict):
        data1_keys = sorted(data1.keys())
        data2_keys = sorted(data2.keys())
        self.assertListEqual(data1_keys, data2_keys)
        for key in data1_keys:
            self.assertEqualUnordered(data1[key], data2[key])
    else:
        self.assertEqual(data1, data2)

In general this code works normal, but if d1 and d2 are dicts, than I've got:

TypeError: unorderable types: dict() < dict()

How can I rewrite it to work in py3k?

Unit testing first, Database Count using LINQ

Since I'm now practicing a unit test first development process I had this question while doing the unit test.

I have to create a test that'll verify or assert the items that it will count in a specific table in the database. Also, it has parameters.

  [TestMethod]
  public void verify_items_count()
  {
      //Arrange
      Mock<IRepository> Repo = new Mock<IRepository>();
      Repo.Setup(t => t.Query().Count(t => t.Id == "**WHAT SHOULD I PUT HERE IF THIS IS ONLY A MOCK**")).Returns(12);

      //Act
      //Assert
  }

Seems like it'll be none sense if I assert it checking if it returns 12 having also its parameters since we all know that it doesn't call in the DB. I've set it to 12, though.

Please help me how to write a unit test first. I was thinking if it is supposed to be in an integration testing. But I've read that everything should start in unit testing. So I believe there is a way.

How to test MFC CWnd based classes using google test/mock?

I am new with the idea of TDD. I have not used any testing framework before. Recently I have started reading about it and practicing with google test. My goal is to start TDD in a legacy code base developed in MFC. Most of the time I have to work with GUI controls - developing new custom controls, adding features to existing custom controls etc. So, I want to automate the testing of GUI classes which are mostly derived from CWnd class.

I have created a win32 console project in Visual Studio for testing, while creating the project I have ticked MFC in 'Add common header files for' option. Visual Studio project wizard has generated the main function and have created a CWinApp object. In the main function I have added the boilerplate code for google test. I have compiled the actual project (that is to be tested) and google test (and mock) library as .lib and linked it to the test project. I have successfully build the test project. I can test simple things from the projects.

Here is wizard generated code (google test boilerplate code included)-

#include "stdafx.h"
#include "TestMFC.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object
CWinApp theApp;
using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(NULL);

    if (hModule != NULL)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            _tprintf(_T("Fatal Error: MFC initialization failed\n"));
            nRetCode = 1;
        }
        else
        {
            // TODO: code your application's behavior here.
              testing::InitGoogleMock(&argc, argv);
              nRetCode = RUN_ALL_TESTS();
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
        nRetCode = 1;
    }
    return nRetCode;
}

The challenge I am facing is I can't create actual window as that will require to have message loop. I wanted to mock CWnd so that I can test features based on know assumptions. But, I can't find a way to mock CWnd as it has some non-virtual member functions that depend on HWND. HWND is valid only if I create a window. Another challenge is message handlers are not virtual functions. So I can't mock message handlers and without creating a window it is not possible to route a message to its handler.

I need thoughts on how can I approach to solve the problem. Can I do it without creating actual window with mock or something else? Or I can create window and route messages?

Thanks in advance.

Writing test cases for wso2 ESB templates or endpoints file

I have to write test cases (Integration testing) to test each service or endpoints which has been integrated within a single Requestpayloadsequence file. Can any one please help me how to do the same to test each endpoints/templates separately.

Below is the payloadsequence file where we are calling many templates, which in turn call endpoints.xml file

abcPayloadSeq_v1.0.0.xml

 <?xml version="1.0" encoding="UTF-8"?>
    <sequence xmlns="http://ift.tt/IrJ6pr" name="abc_v1.0.0" onError="abc_v1.0.0">
        <property name="abc" expression="//abc" scope="default" type="STRING"/>
        <property name="xyz" expression="//xyz" scope="default" type="STRING"/>
        <property name="object1" expression="json-eval($.object1)" scope="default" type="STRING"/>
        <property name="object2" expression="json-eval($.object2)" scope="default" type="STRING"/>
        <property name="object3" expression="json-eval($.object3)" scope="default" type="STRING"/>
        <call-template target="abcTemplate_v1.0.0"/>
        <property name="object5" expression="$body/*" scope="default" type="STRING"/>
        <property name="object6" expression="//object6" scope="default" type="STRING"/>
        <call-template target="Test1123Template_v1.0.0">
            <with-param name="abc123" value="{get-property('abc123')}"/>
            <with-param name="abc456" value="abc456"/>
            <with-param name="abc789" value="abc789"/>
         </call-template>
          <call-template target="Test2Template_v1.0.0">
             <with-param name="xyz123" value="AP106532"/>
            <with-param name="xyz456" value="{get-property('abc456')}"/>
        </call-template>
        <loopback/>
    </sequence>

Test1123Template_v1.0.0.xml file

    <sequence key="GenericCaptureRequest_v1.0.1"/>
    <call-template target="GenericCallBackEndTemplate_v1.0.0">
        <with-param name="backendServiceName" value="abcProducerService"/>
        <with-param name="endpointRef" value="abcEndpoint_v1.0.0.xml"/>
    </call-template>
   <sequence key="GenericCaptureResponse_v1.0.1"/>
</sequence>

Failing to create 'mongoMappingContext' Bean when unit-testing with Fongo

I am currently setting up the unit test for the project I am working on and I have run into a bit of a wall. The project I am working on is using mongoDB as its database so for unit-testing I wanted to use Fongo to simulation the database so I can test just the functionality itself. But whenever I run the tests it fails to properly create the mongoMappingContext Bean and the tests themselves fail. The underlying cause is a mappingException but I am not what is causing that. Has anyone else experienced a similar thing when unit-testing with Fongo? Thanks in an advance for all your help!

The test DB config file, TestDatabaseConfiguration.java:

@Configuration
@Import(value = MongoAutoConfiguration.class)
@PropertySource("classpath:application.properties")
@EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableMongoRepositories("com.x.repository")
@ComponentScan(basePackages = {"com.x.service", "com.x.utility"})
public class TestDatabaseConfiguration extends AbstractMongoConfiguration {
    private final Logger logger = LoggerFactory.getLogger(TestDatabaseConfiguration.class);

    @Override
    protected String getDatabaseName() {
        return "test_app";
    }

    @Override
    public Mongo mongo() throws Exception {
        // uses fongo for in-memory tests
        return new Fongo("mongo-test").getMongo();
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.x.service";
    }

    @Override
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "test_app");
    }

    @Bean
    public CustomConversions customConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        OAuth2AuthenticationReadConverter converter = new OAuth2AuthenticationReadConverter();
        converterList.add(converter);
        return new CustomConversions(converterList);
    }

    @Bean
    public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
        MongoMappingContext mappingContext = new MongoMappingContext();
        mappingContext.setInitialEntitySet(getInitialEntitySet());
        mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder());
        mappingContext.setFieldNamingStrategy(fieldNamingStrategy());

        return mappingContext;
    }

    @Bean
    public MongoDbFactoryBean dbFactoryBean() throws Exception {

        MongoDbFactoryBean dbFactoryBean = new MongoDbFactoryBean();
        dbFactoryBean.setMongo(mongo());

        dbFactoryBean.setName("test_app");

        logger.info("Application database: {}", "test_app");

        return dbFactoryBean;
    }
}

The test file, MarketingAutomationServiceTest.java:

@ContextConfiguration(classes = {TestDatabaseConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class MarketingAutomationServiceTest extends TestCase {

    @Autowired
    private MarketingAutomationService marketingAutomationService;

    @Test
    @UsingDataSet(locations = {"/one-marketing-automation-query.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
    public void testGetQuery(){
        MarketingAutomationQuery result = marketingAutomationService.getQuery("555a3662e4b024fe6d7a9d3f");

        assertNotNull(result);
    }
}

The error trace I am getting from Spring whenever I run the test:

09:51:19.715 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@702657cc] to prepare test instance [null(com.x.service.MarketingAutomationServiceTest)]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoMappingContext' defined in com.x.config.TestDatabaseConfiguration: Invocation of init method failed; nested exception is org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both private final java.lang.reflect.Type org.springframework.data.util.TypeDiscoverer.type and private final java.lang.Class org.springframework.data.util.ClassTypeInformation.type map to the same field name type! Disambiguate using @DocumentField annotation!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    ... 25 common frames omitted
Caused by: org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both private final java.lang.reflect.Type org.springframework.data.util.TypeDiscoverer.type and private final java.lang.Class org.springframework.data.util.ClassTypeInformation.type map to the same field name type! Disambiguate using @DocumentField annotation!
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.assertUniqueness(BasicMongoPersistentEntity.java:264) ~[spring-data-mongodb-1.6.1.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.doWithPersistentProperty(BasicMongoPersistentEntity.java:251) ~[spring-data-mongodb-1.6.1.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.doWithPersistentProperty(BasicMongoPersistentEntity.java:245) ~[spring-data-mongodb-1.6.1.RELEASE.jar:na]
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:294) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.verifyFieldUniqueness(BasicMongoPersistentEntity.java:150) ~[spring-data-mongodb-1.6.1.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.verify(BasicMongoPersistentEntity.java:142) ~[spring-data-mongodb-1.6.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:298) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:607) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:607) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.addPropertiesForRemainingDescriptors(AbstractMappingContext.java:442) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:296) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:607) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:470) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:607) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:257) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.initialize(AbstractMappingContext.java:373) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.afterPropertiesSet(AbstractMappingContext.java:363) ~[spring-data-commons-1.9.1.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    ... 40 common frames omitted