jeudi 31 mars 2016

DOM access methods to get DOM coverage of JavaScript unit tests

It is surprising that there is no DOM coverage tool for JavaScript unit tests. I'm trying to implement DOM coverage for my research. The following code modifies the prototype of 'getElementById' and saves the accessed element to an array. Then, I can know which DOM elements are covered when executing JavaScript unit tests.

var gebi = Document.prototype.getElementById;
Document.prototype.getElementById= function(id) {
  var r= gebi.call(this,id);
  return saveAndReturnEle(r);
}

var accessedElements=[];
function saveAndReturnEle(elem){
   accessedElements.pushIfNotExist(elem,function(e){
     return e === elem;
   });
   return elem;
}

I would like to know what methods I should modify like above to get the DOM coverage of modern Web applications. I'm not sure that modifying following methods are enough.

document.getElementById(id)
document.getElementsByClassName(className)
document.getElementsByTagName(tagName)
document.querySelector(cssSelector)
document.querySelectorAll(cssSelector)

Test Serialization and Deserialization of objects in Java

Earlier, I had a java class:

public enum Currency
{
   PENNY,
   NICKLE,
   DIME,
   QUARTER;
}

Now I have made changes in the class and it looks like this:

public enum Currency
{
    PENNY("Penny"),
    NICKLE("Nickle"),
    DIME("Dime"),
    QUARTER("Quarter");

/**
 * Instantiates a new currency.
 * 
 * @param currencyType the currency type
 */
Currency(String currencyType)
{
    this.value = currencyType;
}

String value;

/**
 * Gets the value
 *
 */
public String getValue()
{
    return this.value;
}

}

I want to check if the Currency class object is getting serialized and deserialized properly. How should I check this through unit testing in java ?

Throwing exception while creating constructor doesn't work

I need to throw MQTTException when the MQTTClient constructor is called, as shown below in the code.

        public MqttClient createClient(String url, String clientId) throws ServiceSDKException {
            if (!(url.isEmpty() || url == null || clientId.isEmpty() || clientId == null)) {
                try {
                    client = new MqttClient(url, clientId);
                } catch (MqttException e) {
                    throw new ServiceSDKException("MqttException occurred when creating a new client", e);
                } catch (IllegalArgumentException e) {
                    throw new ServiceSDKException("Illegal arguments detected, could be malformed url", e);
                }

            } else {
                throw new ServiceSDKException("URL and ClientID cannot be null or empty");
            }
            return client;
        }

     @Override
@PrepareForTest(MqttClient.class)
    @Test(expected = ServiceSDKException.class)
    public void should_throw_ServiceSDKException_when_MqttException_occurs_while_creating_the_client() throws Exception {
        PowerMockito.whenNew(MqttClient.class).withArguments(Matchers.anyString(), Matchers.anyString()).thenThrow(new MqttException(Mockito.mock(Throwable.class)));
        MqttClient client = clientMqtt.createClient("tcp://localhost:1883", "100");
    }

I have added the below line to the class as well.

@RunWith(PowerMockRunner.class)

But I am getting an assertion error saying my exception was not thrown. I tried debugging and it doesn't throw MQTTException as I expect, when creating the client instance. What am I doing wrong here? How do I test this line? Please advice.

Using EvoSuite with JMockit for code coverage

Have created a unit test using EvoSuite and want to use maven build to do code coverage analysis on this unit test. When I run maven build I get ...

JMockit Coverage got reloaded through custom class loader org.evosuite.runtime.instrumentation.EvoClassLoader;

Is it possible to run the EvoSuite unit test through JMockit? Any suggestions?

How to add Test name and module to Test docstring in result?

I am using django_nose's NoseTestSuiteRunner to run tests. Currently if the test has docstring it will be printed on console for the test (TestCase.ShortDescrption()) and if it's None name of the test (TestCase.id()) is printed, I want to add TestCase.id() to TestCase.ShortDescription() so that TestCase.id() is printed regardless of docstring's presence.

sample test:

class Foo(unittest.TestCase):
      def test_bar_1(self):
          """ this is docstring 1"""
          pass

      def test_bar_2(self):
          """ this is docstring 2"""
          self.fail()

so for the result instead of

this is a docstring 1 ... ok
this is a docstring 2 ... Fail

I want

test_bar_1(path.to.test.Foo) this is a docstring 1 ... ok
test_bar_2(path.to.test.Foo) this is a docstring 2 ... Fail

vstest.console.exe runs same tests multiple times

This is the command I use to run all NUnit tests from specified library

vstest.console.exe "PATH_TO_REPOSITORY\Tests\terminalBaseTests\bin\debug\terminalBaseTests.dll" /logger:trx /TestAdapterPath:"PATH_TO_REPOSITORY"

This dll contains 27 tests but I see that they launched for some reason 3 times and the resulting message says that 81 tests were passed

How to test textbox component in asp.net using mvp pattern using NSubstitute, C#?

I'm learning mvp pattern and unit tests in asp.net web forms. I created sample to try make a simple test of textbox component. There is only one form 'Home.aspx' with textbox named 'QuestionContent' and one button named 'SendQuestion'. The code-behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication12
{
    public interface IHomeView
    {
        string QuestionContent_Text { get; set; }
    }

    public partial class Home : System.Web.UI.Page,IHomeView
    {
        private HomePresenter _homePresenter;

        public Home()
        {
            _homePresenter = new HomePresenter(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public string QuestionContent_Text
        {
            get
            {
                return QuestionContent.Text;
            }
            set
            {
                QuestionContent.Text = value;
            }
        }

        protected void SendQuestion_Click(object sender, EventArgs e)
        {
            if (QuestionContent_Text.Count() > 30)
            {
                _homePresenter.SendQuestion_Click();
            }
        }
    }
}

I created presenter class in other file. The code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication12
{
    public interface IHomePresenter
    {
        bool SendQuestion_Click();
    }

    public class HomePresenter : IHomePresenter
    {
        private IHomeView _homeView;

        public HomePresenter(IHomeView homeView)
        {
            this._homeView = homeView;
        }

        public bool SendQuestion_Click()
        {
            //..some code, if sth gone wrong return false

            //message send successfully
            return true;
        }
    }
}

I Created project Unit Test Project. I created class 'HomeTest'. Here is the code:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication12.Tests
{
    [TestClass]
    public class HomeTest
    {

        private HomePresenter _homePresenter;
        private IHomeView _homeView;


        public void Init()
        {
            Home HomeMock = Substitute.For<Home>();

            _homeView = (IHomeView)HomeMock;
            _homePresenter = new HomePresenter(_homeView);
        }

        [TestMethod]
        public void CheckIfMessagePassedValidationAndSentProperly_GivenSampleText31Length_ReturnsTrue()
        {
            Init();


            bool result=false;

            _homeView.QuestionContent_Text = "0123456789001234567890012345678901"; //length=31

            if (_homeView.QuestionContent_Text.Count() > 30)
            {
                result = _homePresenter.SendQuestion_Click();
            }

            Assert.IsTrue(result);

        }
    }
}

I created method to test if length of QuestionContent textbox content is greater than 30. If yes invoke _homePresenter.SendQuestion_Click() method. When I run test method I get error: "Object reference not set to an instance of an object." on line of code

_homeView.QuestionContent_Text = "0123456789001234567890012345678901"; 

My first thought was to add TextBox QuestionContentControl { set; } to IHomeView, then implement it in Home class:

 public TextBox QuestionContentControl
 {
    set
    {
        QuestionContent = value;
    }
 }

and then create mock in my test method:

_homeView.QuestionContentControl = Substitute.For<TextBox>();

I implemented that solution and all worked properly but I dont think it is a good practise cuz I won't use public TextBox QuestionContentControl in my production code. I will use it only for tests. Can somebody tell me if I'm right with my suggestion that create public TextBox QuestionContentControl is not a good practise and give me an alternative how to make test to CheckIfMessagePassedValidationAndSentProperly ?

Mock a method for test

Trying to mock a method that is called within another method.

public virtual bool hello(string name, int age)
{

    string lastName = GetLastName();
}

 public virtual string GetLastName() 
    {
        return "xxx"; 
    }

 Mock<program> name= new Mock<program>();
 name.Setup(x => x.GetLastName()).Returns("qqq");

I want the method GetLastName to always return "qqq".

Unit Test for Writing to a Text File [duplicate]

This question already has an answer here:

I am trying to write a unit test to make sure that the method is writing to a text file. My method writes to the text file MovieList.txt. I kept getting an error saying that it cannot access the file because it is being used by another process. So I tried changing the method to accept a parameter to write to a different text file, MovieListTEST.txt, but I still can't figure it out. Anyone know how to properly do this?

This is my code to write to the file:

public bool WriteMovieListToFile()
{
    try
    {
        FileStream fs = new FileStream("MovieList.txt", FileMode.Append, FileAccess.Write);
        StreamWriter textWriter = new StreamWriter(fs);

        textWriter.WriteLine(movie.Title);
        textWriter.WriteLine(movie.Genre);
        textWriter.WriteLine(movie.Actor);
        textWriter.WriteLine(movie.Year);

        textWriter.Close();
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error:" + ex.Message);
        return false;
    }
}

Edited with param:

public bool WriteMovieListToFile(string fileLocation)
{
    try
    {
        FileStream fs = new FileStream(fileLocation, FileMode.Append, FileAccess.Write);
        StreamWriter textWriter = new StreamWriter(fs);

This is my unit test code:

/// <summary>
///A test for WriteMovieListToFile
///</summary>
[TestMethod()]
public void WriteMovieListToFileTest1()
{
    Movie movie1 = new Movie("Title", "Genre", "Actor", "Year");
    movieSystem.AddMovie(movie1);
    movieSystem.WriteMovieListToFile("MovieListTEST.txt");

    var fileText = File.ReadLines("MovieListTEST.txt");
    Assert.IsTrue(fileText.ToString().Length > 1);
}

MiniTest assert_response messages?

Can you specify which error message that you get when using assert_response? I have a series of validations that all trigger 422 errors and I'm currently testing that they trigger using

assert_response(422)

Is it possible to be more specific and test which 422 I produced?

unit testing $watch of a directive that requires itself

I am having some trouble unit testing the watch method of my directive. The directive requires the its own direcitive so ctrl houses one main method updateHeight

In my controller I have one method

 this.updateHeight = function (clientHeight) {
    $rootScope.haGlobalAlerts.clientHeight = clientHeight;
};

Inside of my link function I am calling this

 ctrl.updateHeight(el.clientHeight);

I have a $watch method that looks for changes

  $scope.$watch(function () {
    return el.clientHeight;
  },
    function (newHeight, oldHeight) {
        if (first || (newHeight !== oldHeight)) {
           first = false;
           ctrl.updateHeight(newHeight);
         }
    });

Identifying how to test and mock a change is really confusing me. In my directive I created scope like so ....

 html = angular.element("<div global alerts> </div>")
 element = $compile(html)($rootScope);

 $rootScope = $rootScope.$new()

 // added this to get update height

 controller = element.controller('GlobalAlerts')

 //setting controller gives me access to controller.updateHeight().

 scope = element.scope();

scope does not have access to this. I am not sure how to make a call to it.

If I call

controller.updateHeight() //It is not changing the value.

In my test I have $apply called on the scope

scope.$apply()

Here is my complete test

 it("should update client Height", function () {

        expect(element[0].clientHeight).to.equal(0);
        var newHeight = 20;
        controller.updateHeight(newHeight);
        scope.$apply();
        expect(element[0].clientHeight).to.equal(20);
    });

Leaflet plugin not available in AngularJS controller during unit tests

I'm using Karma + Mocha to test a controller in Angular. The code below is a simplified example of the controller & test spec. L.Control.Locate is a LeafletJS plugin.

The problem

During a test run L.Control.Locate should exist when the controller is instantiated, but it doesn't. It throws: TypeError: L.Control.Locate is not a constructor.

The app works as expected in the browser.

The error occurs in both PhantomJS and Chrome.

In the test I've confirmed with a debugger that before MapCtrl2 is instantianted, L.Control.Locate is declared and attached to window.L.Control as it should be, but it's getting lost before the controller is instantiated.

The other standard properties for L are there as expected.

When I paste L.Control.Locate.js into the file before the controller declaration, the error disappears.

I've also tried injecting $window into the controller and looking at $window.L.Control.Locate, but it's still undefined.

Thanks for any clues.

Code:

angular.module('app')
.controller('MapCtrl2', function ($scope) {

  // Throws error here.
  var locateControl = new L.Control.Locate();

  // Do something with locateControl.

});

describe('MapCtrl2', function () {

  var controller, scope;
  beforeEach(module('app'));
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    controller = $controller('MapCtrl2', {
      $scope: scope
    });
  }));

  it('has L.Control.Locate', function() {
    expect(window.L.Control.Locate).to.be.an.instanceOf(Object)
  });

});

Unit Testing an injected service within an Angular Controller

I have the following Angular Controller and Service setup (in Typescript) in my app and I would like to write tests for them (using Jasmine, Karma and PhantomJS).

See below for error.

For full source code, see: http://ift.tt/22T2XoU

MainController.ts

namespace app.controllers {

export class MainController implements app.Interfaces.IMainController {

    public city: string;
    public departures: Interfaces.IQueryResult;
    public arrivals: Interfaces.IQueryResult;
    public error: string;
    public time: number;
    public nationalRail: Interfaces.INationalRailService;

    static $inject: Array<string> = ['nationalRail', '$interval', '$routeParams'];
    constructor(nationalRail: app.Interfaces.INationalRailService, private $interval: ng.IIntervalService, private $routeParams: Interfaces.IParameters) {
        this.nationalRail = nationalRail;
        this.city = $routeParams.City;
        this.GetData();
        this.$interval(() => {
            this.GetData();
        }, 60000);
        this.$interval(() => {
            this.time = Date.now();
        }, 1000);
    }

    GetData(): void {
        this.nationalRail.getDepartures(this.city).then((data: app.Interfaces.IQueryResult) => {
            this.departures = data;
            this.error = null;
        }, () => { this.error = "Unable to load data for '" + this.city + "'"; });

        this.nationalRail.getArrivals(this.city).then((data: app.Interfaces.IQueryResult) => {
            this.arrivals = data;
            this.error = null;
        }, () => { this.error = "Unable to load data for '" + this.city + "'"; });
    }
}

var appModule = angular.module('nationalRailViewer')
appModule.controller('MainController', ['nationalRail', '$interval', '$routeParams',
    (nationalRail: app.Interfaces.INationalRailService, $interval: ng.IIntervalService, $routeParams: Interfaces.IParameters) => new MainController(nationalRail, $interval, $routeParams)]);
}

NationalRailService.ts

namespace app.services {
export class NationalRailService implements app.Interfaces.INationalRailService {

    http: ng.IHttpService;

    static $inject: Array<string> = ['$http'];
    constructor($http: ng.IHttpService) {
        this.http = $http;
    }

    getDepartures(city: string): ng.IPromise<app.Interfaces.IQueryResult> {
        return this.http.get("http://ift.tt/1X0P3dl" + city)
            .then(function(response) {
                return response.data;
            });
    }

    getArrivals(city: string): ng.IPromise<app.Interfaces.IQueryResult> {
        return this.http.get("http://ift.tt/22T2XoW" + city)
            .then(function(response) {
                return response.data;
            });
    }
}

angular.module('nationalRailViewer')
    .service('nationalRail', ['$http', ($http: ng.IHttpService) => new NationalRailService($http)]);
}

I'd like to write a test that ensures the getDepartures and getArrivals functions are called on instantiation of the controller. So far I have the following spec.

controllerSpec.ts

describe("MainController Controller", function() {
var httpbackend: ng.IHttpBackendService;
var controller: app.Interfaces.IMainController; 
var interval: ng.IIntervalService;
var routeParams: app.Interfaces.IParameters;
var nationalRail: app.Interfaces.INationalRailService;

var $controller: ng.IControllerService;  

beforeEach(angular.mock.module("nationalRailViewer"));

beforeEach(() => angular.mock.inject(function($http: ng.IHttpService, 
                            $httpBackend: ng.IHttpBackendService,
                            _nationalRail_: app.Interfaces.INationalRailService,
                            $controller: ng.IControllerService, 
                            $interval: ng.IIntervalService, 
                            $routeParams: app.Interfaces.IParameters) {

    interval = $interval;
    routeParams = $routeParams;
    routeParams.City = "aberdeen";
    httpbackend = $httpBackend;
    nationalRail =  _nationalRail_;
    $controller = $controller;
}));

it("Should call getDepartures on NationalRailService", () => {      
    spyOn(nationalRail, "getDepartures").and.callFake(() => {});
    controller = $controller<app.Interfaces.IMainController>('MainController', { nationalRail: nationalRail, $interval: interval, $routeParams: routeParams});
    expect(httpbackend.expectGET("/departures/aberdeen")).toHaveBeenCalled();
    httpbackend.flush();
});

it("Should call getArrivals on NationalRailService", () => {
    spyOn(nationalRail, "getArrivals").and.callFake(() => {});
    controller = $controller<app.Interfaces.IMainController>('MainController', { nationalRail: nationalRail, $interval: interval, $routeParams: routeParams});
    expect(httpbackend.expectGET("arrivals/aberdeen")).toHaveBeenCalled();
    httpbackend.flush();
});
});

For some reason the injections don't seem to be working and I can't run any of my tests without getting the following error:

Error: spyOn could not find an object to spy upon for getArrivals()

Or similar error for the following test, if I comment out the previous.

Why is my inject function not injecting the correct objects?

Unit testing AngularJS application with karma-browserify

I'm trying to unit test an AngularJS/Browserify application via karma-browserify. Ultimately, when I run my gulp karma task, I get the error Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it...

My gulpfile.js has the task

gulp.task('test', function(done) {
    new karma.Server({
        configFile: __dirname + '/karma.conf.js'
    }, done).start();
});

My karma.conf.js includes

{
  // ...
  frameworks: ['browserify', 'jasmine'],
  files: [
    'node_modules/angular/angular.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'spec/**/*.js'
  ],
  preprocessors: {
    'spec/**/*.js': [ 'browserify' ]
  },
  browserify: {
    debug: true
  }
  // ...
}

I define my module in a main.js that includes

require('angular').module('myApp', [
  //...lots of `require`s for each dependency...
]);

I define my controller in a MainCtrl.js that looks like

function MainCtrl(/*...deps...*/) {
  var ctrl = this;
  ctrl.foo = 'bar';
}

module.exports = MainCtrl;

then register the controller elsewhere like

var app = require('angular').module('myApp');
app.controller('MainCtrl', [/*...deps...*/, require('./MainCtrl')]);

Finally my test looks like

(function() {
    "use strict";

    describe('MainCtrl', function() {
        var ctrl;

        beforeEach( angular.mock.module('myApp') );

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

        it('should be defined', function() {
            expect(ctrl).toBeDefined();
        });
    });
}());

Workaround

The workaround I have is to add my main.js file to karma.conf.js

files: [
  'js/main.js', // ADDED: Defines the app and `require`s angular
  'node_modules/angular-mocks/angular-mocks.js',
  'spec/**/*.js'
],
preprocessors: {
  'js/main.js': ['browserify'], // ADDED
  'spec/**/*.js': ['browserify']
}

and everything works. But I thought I wasn't supposed to add my source files to karma (at least not with karma-browserify). Is this the right way to set up my project?

JS unit test mocking a var in jest

How can I mock an array in Jest? I want my unit test to use the mocked value of an array in JS.

console.log("inside getStatusAsync:" + listOfsubscriptionId); //gives me undefined

'use strict';

const React = require('react-native');

var listOfsubscriptionId;


const moduleReadyPromise = new Promise(function(resolve, reject) {
    const moduleReadySubscription = subscribeToListner(async (result) => {
        listOfsubscriptionId = result.listOfsubscriptionId;
        resolve();
        unsubscribe(moduleReadySubscription);
    });
});


function subscribeToListner(listener) {
    return EventEmitter.addListener(
        NativeModule.Event,
        listener
    );
}


function unsubscribe(subscription) {
    subscription.remove();
};

const ExportedModule = {};
ExportedModule.getModuleReadyPromise = () => {
    return moduleReadyPromise;
};

ExportedModule.setSubscriptionList = (list) => {
    listOfsubscriptionId = list;
};


ExportedModule.getStatusAsync = async(topic) => {
    console.log("inside getStatusAsync:" + listOfsubscriptionId);
    await ExportedModule.getModuleReadyPromise();
    return xxx
};

module.exports = ExportedModule;

Here is the Test File

'use strict';

require('regenerator/runtime');

const listOfsubscriptionIdTest = ["XXX", "YYY"];

jest.setMock('react-native', REACT_MOCK);

jest.dontMock('../Module');
const Module = require('../Module');


describe('Notifications', () => {
    beforeEach(() => {
        // Module.listOfsubscriptionId = listOfsubscriptionIdTest; // DOES NOT WORK
        // Module.listOfsubscriptionId = jest.fn(() => listOfsubscriptionIdTest); // DOES NOT WORK

        // Module.setSubscriptionList(listOfsubscriptionIdTest);  // WORKS
    });

        pit('should be able to call Native getStatusAsync', async() => {
            await Module.getStatusAsync('XXX');
            expect(NATIVE_MODULE_MOCK.getStatusAsync).toBeCalledWith('XXX');
        });
});

Which approach is best to unit test composed code?

Say I have the following AngularJs service:

angular.module("foo")
    .service("fooService", function(){
        var svc = this;

        svc.get = function(id){...};
        svc.build = function(id){...};
        svc.save = function(thing){...}; //posts, then returns the saved thing
        svc.getOrCreate = function(id){
            return svc.get(id).then(function(thing){
                return thing || svc.build(id).then(function(builtThing){
                    return svc.save(builtThing);
                });
            });
        }
    });

I can unit test the get method by making sure the right API endpoint is being reached, with the right data.

I can test the build method by making sure it pulls data from the proper endpoints/services and builds what it's supposed to.

I can test the save method by making sure the right API endpoint is being reached.

What should I do to test the getOrCreate method? I get two differing opinions on this:

  1. stub the get, build and save methods and verify they're called when appropriate, and with the proper parameters
  2. stub the API endpoints that are being called in get and build, then verify that the endpoints within save are being called with the proper parameters

The first approach is basically saying, "I know these three methods work because they're independently tested. I don't care how they actually work, but I care that they're being called within this method."

The second approach is saying, "I don't care about how this method acts internally, just that the proper API endpoints are being reached"

Which of these approaches is more "correct"? I feel the first approach is less fragile since it's independent of how the get, build and save methods are implemented, but it's not quite right in that it's testing the implementation instead of the behavior. However, option 2 is requiring me to verify the behavior of these other methods in multiple test areas, which seems more fragile, and fragile tests make people hate programming.

This is a common tradeoff I find myself facing quite often with tests... anybody have suggestions on how to handle it?

Jasmine Unit testing for javascript case coversion

I am trying to unit test value conversion to uppercase on keyup.

e.currentTarget.value=$(e.target).val().toUpperCase();

Please provide your valuable input.

thanks in advance.

How to write unit test for ParameterBindingAttribute?

I wrote a custom ParameterBindingAttribute that simply does:

  • Check if there are any parameters passed in the URI. If there are any, parse them and try to match with the model. If it fails, then fail.
  • If no parameters are found, then look at the body. Analogically, parse the body.

My code seems to be working. I've tested various scenarios in Postman (extension for Google Chrome) and it passed it. However, it would be best to write some unit tests for this. Could you give me some guidelines on how to perform such unit testing? Thanks.

Here is the code:

public class FromUriOrBodyAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor descriptor)
    {
        return new FromUriOrBodyParameterBinding(descriptor);
    }
}

public class FromUriOrBodyParameterBinding : HttpParameterBinding
{
    private readonly HttpParameterBinding defaultUriBinding;
    private readonly HttpParameterBinding defaultFormatterBinding;

    public FromUriOrBodyParameterBinding(HttpParameterDescriptor descriptor)
        : base(descriptor)
    {
        this.defaultUriBinding = new FromUriAttribute().GetBinding(descriptor);
        this.defaultFormatterBinding = new FromBodyAttribute().GetBinding(descriptor);
    }

    public override Task ExecuteBindingAsync(
        ModelMetadataProvider metadataProvider,
        HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {
        var query = actionContext.Request.RequestUri.Query;

        return string.IsNullOrWhiteSpace(query)
            ? this.defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)
            : this.defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
    }
}

Pod linking error raised when do Swift unit test on XCode7 if enable "Gather coverage data"

I do a simple swift project using XCode7.3. Everything is ok, UI & Unit test run properly too. However, when I wanna see coverage data, I can not run unit test anymore

ld: framework not found Pods_MapView
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Would you please give me a clue?

P/S: I hostes my project at http://ift.tt/1UFsmhw

Managing the order of testing helper files with Typescript

I am building Angular.js application based on gulp building system and decided to move to typescript. I don't use the module system for managing source files as I have gulp-angular-filesort that handles the ordering.

Never the less there is still one place in the application where I could use some module loader/manager.

Before execution of my unit tests (Jasmine) I need to set up big mock data sets. As they are used in different test files, I've moved them out into *spec.factory.js files for readability and having single responsibility. The issue is that I can't just include all *spec.factory.js because the order of some files matter.

I have file responsible for single item in response collection item.spec.factory and file where the response is created - read collection from items is formed - response.spec.factory.

I'm using karma to run this and wonder if there is a way to require item.spec.factory in the response.spec.factory file by Typescript means, so I can abandom specifying the order of files in karma.conf.js and just add there one line: *spec.factory.js to get all factories.

reusability of tests (Python, unittest, selenium)

What's the best way to reuse my set of test on different stage server? The only thing to change is base_url in config.py. But it's silly to copy all the tests and change one line of code...any ideas?

Terminal colors running test-unit in Rails

I can't seem to make colors work when running test unit in rails. I have tried so far:

  • $ bundle exec bin/rake test TESTOPTS="--use-color" -> It tells me that --use-color is an invalid option.
  • I made a file called test-unit.yml with:

    runner: console
    console_options:
      arguments: --use-color=yes
    
    

still nothing.

  • Following the docs (http://ift.tt/1RNjSOc) I added:

    runner: console
    console_options:
      color_scheme: personal
    color_schemes:
      personal:
        success:
          name: green
          bold: true
        failure:
          name: red
          bold: true
    
    

Still nothing!

Do I need anything else?

Ruby version: 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

Rails version: Rails 4.2.6

Mockito Mock run Autowired class Object

I have below class scenario. While testing MyTestableClass, I wish to process Autowired class. I would like to mock only variable in AutoWired class.

sample class is as below-

public class MyTestableClass {

    @Autowired
    private MyServiceClass service;

    public void handleError(){
    ...
    service.doSomething();

    }
}

public class MyServiceClass {

    @Autowired
    private JMSChannel channel;

    public void doSomething(){
        System.out.println("Inside Service class");
        .....
        channel.isAvailable();
        .....   
    }
}

@RunWith(MockitoJUnitRunner.class)
public class  MyTestableClassTest {
    private MyTestableClass  testClass= new MyTestableClass();

    private JMSChannel channel;

    @Before
    public void init(){
     channel= mock(JMSChannel.class);
     when(channel.isAvailable()).thenReturn(Boolean.TRUE);  
    }

    @Test
    public void test(){
        testClass.handleError();
    }
}

For example, Console should give me "Inside Service class" before returning true.

Thanks in Advance !

Android Unit Test: How to mock a listener that is sent as argument to an asynchronous method?

I have a method that receives a listener (interface) with onSuccess(result) and onFail(error) methods.
The tested method performs some actions (on another thread) and eventually calls the listener with an answer.

Example code for the method itself (not the test):

testedObject.performAsyncAction("some data", new IListener(){
    @Override
    public void onSuccess(int result) {
        if (result == 1) { /* do something */ }
        else if (result == 2) { /* do something else */ }
    }

    @Override
    public void onFailure(Error error) {
        if (error.getMessage().equals("some error")) { /* do something */ }
        else if (error.getMessage().equals("another error")) { /* do something else */ }
    }
});

I want to have few tests on this method:

  • Success when onSuccess(1) is called
  • Success when onSuccess(2) is called
  • Success when onFailure(new Error("some error")) is called
  • Success when onFailure(new Error("another error")) is called

Thank you!

TypeError: Object function has no method 'myMethod' , why cant find mocked method?

I already was looking for this question and found this question, but I cant see the connection to my problem :/

So this is my main.js file:

module.exports = function(client) {

    this.HangUpCall = function(caller,callback) {
        client.calls(caller).update({status: 'completed'}, function(err, call) {
            if(err) {
                console.log(err);
            }
        });
        callback();
    };
}

And I want to mock client. So I made a mock model like this:

module.exports = function() {
    this.calls = function(callSid){
            var update = function(obj,cb){
                console.log(obj);
                cb(false,true);
            };
    };
};

And here is the test file:

describe("testing HangUpCall",function(){
        it('should update caller status to completed',function() {
            var Client = require(__dirname +'path/Mockfile');
            var mockClient = new Client();
            EMGC = new MAINFILECONSTRUCTOR(twilio, Client, mockClient);
            EMGC.HangUpCall('CA1234',function(){

            });
        });
});

And yeah this is what the console sais:

TypeError: Object function () {
    this.calls = function(callSid){
            var update = function(obj,cb){
                console.log(obj);
                cb(false,true);
            };
    };
} has no method 'calls'

Launch junit/robolectric tests (gradle)

I have my unit/Robolectic tests located in

/app/src/test/java

This is made to distinguish android instrumentation tests located in /app/src/androidTest/java

How can I only run these unit tests which don't need whole project to be built (which is time consuming) from command line?

Is there any gradlew/java command?

I want to obtain the same result as if running from Android Studio junit tests from specific dir.

Python Unit Test: Mimic a command line argument for test purposes

I am writing a unit test for the following function which is in my_script.py:

def _parse_args():
    parser = argparse.ArgumentParser(
        description='Script to configure appliance.'
    )
    parser.add_argument('--config_file',
                        help='Path to a JSON configuration file') 
    print parser.parse_args()
    return parser.parse_args()

I want to create a unit test to mimic the command line prompt:

myscript.py --config_file test.json

This is what I have so far:

def test_parse_arg_test_config(self):

        test ={
                "name": "test_name",
                "category": "test_category"
            }

        # set the fake command line prompt to be:
        # myscript.py --config_file test
        # (where test is defined above)

        self.assertEquals(my_script._parse_args().config_file, test)

It is obviously incomplete, but I was wondering if I am approaching this the correct way since _parse_args doesn't take in any inputs I don't know a different way to mimic a config file being passed into the function.

Laravel API Test - How to test API that has external API call

My API code

public function store (Request $request, $profileId)
{
    $all = $request->all();
    $token = AccessToken::with('users')->where('access_token',$request->input('access_token'))->first();

    if($token && $token->users->isOwnProfile($profileId))
    {
        $rules = [
            'access_token'     => 'required',
            'title'            => 'required',
            'description'      => 'required',
            'file_id'          => 'required',
            'audience_control' => 'required|in:' . join(',', PostRepository::$AUDIENCE_CONTROL),
            'tags'             => 'required',
        ];
        $validator = Validator::make($all, $rules);

        $error = $validator->errors()->toArray();
        if ($validator->fails())
        {
            return $this->setStatusCode(401)
                ->setStatusMessage(trans('api.validation failed'))
                ->respondValidationMessage($error);
        }
        try {
            $response = $this->postRepository->save($request, $profileId);
            if(isset($response['error']))
                return $this->messageSet([
                    'message' => $response['error']['message'],
                ], $response['error']['status_code']);

            return $this->setDataType('post_id')
                ->setStatusCode('200')
                ->respondWithCreatedId(trans('api.Post created'), $response->id);
        } catch (\Exception $e) {
            return $this->respondInternalError(trans('api.processing error'));
        }
    }
    return $this->respondInternalError('404 page');

}

From save method it calls another method that calls an external API.

/*
 * this function returns some response where it has profile_id for 
 * the file which in other save function is matched that the
 * profile_id passed as parameter is same with file profile_id
 */
public function getFileDetails($file_id)
{
    try
    {
        $response = json_decode((new Client())->request('GET', env('xyz','http://abc.xyz/api/v1').'/files/' . $file_id)->getBody()->getContents(), true);
    }
    catch (RequestException $e)
    {
        $response = json_decode($e->getResponse()->getBody()->getContents(), true);
    }

    return $response;

}

Now this is my test function for API.

public function testPostCreateChecksProfileMatchesCorrectly()
{
    $this->json('POST', 'profiles/' . $this->getProfile()->id . '/posts' . '?access_token=' . $this->getAccessToken(), [
        'title' => 'api testing title',
        'description' => 'api testing description',
        'audience_control' => 'public',
        'tags' => [
            'Animals',
            'City'
        ],
        'file_id' => '281'
    ])->seeJsonStructure([
        'success' => [
            'message',
            'post_id',
            'status',
        ],
    ]);
}

Now my question is how can I create a fake response for the external API when I am testing.

I am using PHPUnit & Laravel 5.2.

Python Unit test: Assertion Error issue

I am writing a unit test for the following function:

def _parse_args():
    parser = argparse.ArgumentParser(
        description='Script to configure appliance.'
    )
    parser.add_argument('--config_file',
                        help='Path to a JSON configuration file') 
    print parser.parse_args()
    return parser.parse_args()

When I run the function when no config file is given then (verified using the print statement in the function above): parser.parse_args()=Namespace(config_file=None)

In my unit test I run the function with no config file given and include an assertEquals:

self.assertEquals(my_script._parse_args(), 'Namespace(config_file=None)')

But this produces the AssertionError:

AssertionError: Namespace(config_file=None) != 'Namespace(config_file=None)'

If I change the unit test to without the quotation marks:

self.assertEquals(my_script._parse_args(), Namespace(config_file=None))

I get a NameError:

NameError: global name 'Namespace' is not defined

Clearly using quotations is not the correct way to do this but how do I get it to assert that Namespace(config_file=None) is occurring?

how to unit test a code which uses Java UUID

I have a piece of code which is expected to populated one attribute of response object with java UUID (UUID.randomUUID())

How can I unit test this code from outside to check this behaviour as I don't know the UUID that would be generated inside it?

Any suggestions please?

Sample code which needs to be tested

//To test whether x attribute was set using an UUID
// instead of hardcode value in the response
    class A {
    String x;
    String y;
    }
    public a doSomething() {
    //Does something
    A a = new A();
    a.setX( UUID.randomUUID());
    return a;
    }

Thanks, Harish

ClassCleanup method not being called in Visual Studio Unit Test

I have a simple unit test class in Visual Studio, in which a class is attributed with ClassCleanup.

But this method only gets called if I debug the test and is not called when I simply run the test.

Here is how my simple test class looks

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace UnitTests
{
    [TestClass]
    public class ExampleTests
    {
        private static readonly Guid UniqueDbId = Guid.NewGuid();

        [ClassInitialize]
        public static void Init(TestContext testContext)
        {
            DbSetup.Init(UniqueDbId);
        }

        [ClassCleanup]
        public static void Cleanup()
        {
            DbSetup.Cleanup(UniqueDbId);
        }

        [TestMethod]
        public void DummyTest()
        {
            Assert.IsTrue(true);
        }
    }
}

To prove my point, the method attributed as ClassCleanup calls this method

public static void Cleanup(Guid uniqueDbId)
{
    throw new Exception("This happened");
}

The exception is only thrown when in debug mode.

I've verified this several other ways, such as writing to a log file. I noticed this because the ClassInitialize method creates a database for the tests and the ClassCleanup method should then delete this database but again, it only gets deleted if I run in debug mode.

I believe I've followed the ClassCleanup example on MSDN.

Can anyone explain why the ClassCleanup method is not running when I simply run the tests, i.e., not debugging?

Unit testing $httpBackend angular no response defined

I'm struggling in my first test so please bear with me. I want to test a function that make a http post:

$scope.formData= 'client=' + $scope.client_selected + '&version=' + $scope.version_selected + '&modules=' + $scope.client.modules;
        var response = $http.post('http://localhost:8080/mavenproject8/lol/form', $scope.formData);
        response.success(function (data, status, headers, config) {
            $scope.validity = true;
            $scope.status = "true";
        });
        response.error(function (data, status, headers, config) {
            $scope.status = "false";
            alert("Exception details: " + JSON.stringify({data: data}));

and my test looks like this:

...
beforeEach(inject(function ($injector) {
    // Set up the mock http service responses
    $httpBackend = $injector.get('$httpBackend');
    $httpBackend.when('POST', 'http://localhost:8080/mavenproject8/lol/form', data)
            .respond([200, {success: true, errors: [{}]}]);

and this is the it block:

it('should succeed when everything is correct', function () {
    $rootScope.client.modules=["360"];
    $rootScope.version_selected="2.4.0"
    $rootScope.client_selected="NSM";
    $rootScope.formData='client=' + $rootScope.client_selected + '&version=' + $rootScope.version_selected + '&modules=' + $rootScope.client.modules;
    $httpBackend.expectPOST('http://localhost:8080/mavenproject8/lol/form',$rootScope.formData);
    $rootScope.myFunc();
    expect($rootScope.validity).toBe(true);
});

But this test doesn't pass, with the error:

Error: No response defined !

I feel like I'm so close but I can't make it work. I would be grateful if you could help me. Thank you!

flask/sqlalchemy unittest OperationalError: (sqlite3.OperationalError) no such table, but was able to query table previously

I'm trying to write unittests for my Flask api app. I am able to insert an object into my table in one test method, but then in the next test method I get the following error:

OperationalError: (sqlite3.OperationalError) no such table

database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

models.py

from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.orm import validates
from validate_email import validate_email

from database import db_session, Base

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(50))
    last_name =Column(String(50))
    email = Column(String(120), unique=True)


    def __init__(self, first_name=None, email=None):
        self.first_name = first_name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.first_name)

@validates('email')
def validate_email(self, key, email):
    if email is None:
        raise ValueError(
            'Email is required')
    if not validate_email(email):
        raise ValueError(
            "Invalid Email Address")
    if User.query.filter(User.email==email).first():
        raise ValueError(
            "Email exists")
    return email

Lines that run fine:

        user = User(first_name=fname, email=email)
        db_session.add(user)
        db_session.commit()

Subsequent line that is causing error:

        user = User.query.filter(User.id == user_id).first()

my api.py starts with

app = Flask(__name__)
api = Api(app)
init_db()

Does anyone have any ideas for me?

How to combine Mockito and Spring in TestNG

We are building an application which uses Spring Boot. We write unit tests using TestNG and Mockito. However I find it pretty annoying to write when(...) configuration, I would like to use real components instead. I started to use @Spy components instead of mocks and this works pretty well until I need to put a Spy into a Spy. I'd like to avoid loading a Spring Context if possible, because creation of the context is very slow it looks like overkill for me to load it for at max 5 classes.

Is there any way, how could I use real code instead of Mocks and not loading whole Spring context? Or is my approach wrong at all and I should mock out all other classes then the tested one?

No Karma report on singlerun = false

I wonder if I am missing something trivial here, but I can not see any test reports if I have set up singlerun to true in karma config. It only shows that the browsers were launched and that is it. I can click on DEBUG and inspect the browser console log that way, but I would feel that one should be also see the results in the terminal too.

Thanks for the help!

My karma.config.js:

basePath: '../',

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

frameworks: ['mocha', 'chai'],

files: [
  { pattern: 'test/vendor/indexeddbshim.min.js', watched: false },
  { pattern: 'tests.webpack.js', watched: false },
],

preprocessors: {
  'tests.webpack.js': ['webpack'],
},

webpack: {
  resolve: {
    root: [
      path.resolve('./test/vendor'),
    ],
    alias: {
      backbone: 'backbone',
      underscore: 'underscore',
    },
  },
  module: {
    loaders: [
      {
        // test: /^\.js$/,
        exclude: /(node_modules|bower_components|vendor)/,
        loader: 'babel-loader',
      },
    ],
  },
},

webpackServer: {
  noInfo: true,
},

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

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

// web server port
port: 9876,

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

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

plugins: [
  require('karma-webpack'),
  require('karma-mocha'),
  require('karma-chai'),
  require('karma-phantomjs-launcher'),
  require('karma-chrome-launcher'),
],
logLevel: config.LOG_INFO,   }); 

How can a unit test "test the contract" on a method that returns void?

Java 8 here but this is a general unit testing question that (is likely) language-agnostic.

The syntax of writing a JUnit test is easy, but deciding on what tests to write and how to test main/production code is what I find to be the biggest challenge. In reading up on unit testing best practices, I keep hearing the same thing over and over again:

Test the contract

I believe the idea there is that unit tests should not be brittle and should not necessarily break if the method's implementation changes. That the method should define a contract of inputs -> results/outcomes and that the tests should aim to verify that contract is being honored. I think.

Let's say I have the following method:

public void doFizzOnBuzz(Buzz buzz, boolean isFoobaz) {
    // wsClient is a REST client for a microservice
    Widget widget = wsClient.getWidgetByBuzzId(buzz.getId());

    if(widget.needsFile()) {
        File file = readFileFromFileSystem(buzz.getFile());

        if(isFoobaz) {
            // Do something with the file (doesn't matter what)
        }
    }

    return;
}

private File readFileFromFileSystem(String filename) {
    // Private helper method; implementation doesn't matter here EXCEPT...
    // Any checked exceptions that Java might throw (as a result of working)
    // with the file system are wrapped in a RuntimeException (hence are now
    // unchecked.

    // Reads a file from the file system based on the filename/URI you specify
}

So here, we have a method we wish to write unit tests for (doFizzOnBuzz). This method:

  • Has two parameters, buzz and isFoobaz
  • Uses a class property wsClient to make a network/REST call
  • Calls a private helper method that not only works with the external file system, but that "swallows" checked exceptions; hence readFileFromFileSystem could throw RuntimeExceptions

What kinds of unit tests can we write for this that "test the contract"?

Validating inputs (buzz and isFoobaz) are obvious ones; the contract should define what valid values/states for each of those are, and what exceptions/results should occur if they are invalid.

But beyond that, I'm not really sure what the "contract" here would even be, which makes writing tests for it very difficult. So I guess this question really should be something like "How do I determine what the contract is for a unit test, and then how do you write tests that target the contract and not the implementation?"

But that title would be too long for a SO question.

Mocking a bit stream reader with Mockito

I am currently debugging a rather complicated algorithm that fixes errors in a bit stream. A BitReader interface is quite simple, and the main reading method is like this:

/**
  Reads bits from the stream.
  @param length number of bits to read (<= 64)
  @return read bits in the least significant bits
*/
long read(int length) throws IOException;

The objective is to test whether BitStreamFixer actually fixes the stream (in a way that is too hard to describe here). Basically I need to provide “broken” inputs to it and test whether its output is as correct as it can be (some inputs can't be fixed completely), like this:

BitStreamFixer fixer = new BitStreamFixer(input);
int word1 = fixer.readWord();
int word2 = fixer.readWord();
// possibly a loop here
assertEquals(VALID_WORD1, word1);
assertEquals(VALID_WORD2, word2);
// maybe a loop here too

Now, the BitStreamFixer class accepts an instance of BitReader. When unit testing the fixer, I obviously need one such instance. But where do I get one? I have two obvious options: either give it a real implementation of BitReader or mock it.

The former option is not really appealing because it would create a dependency on another object which has nothing to do with the class being tested. Moreover, it's not that easy because existing BitReader implementations read form input streams, so I'll need either a file or somehow prepared byte array, which is a tedious thing to do.

The latter option looks better and fits the usual unit testing approach. However, since I'm not even supposed to know what arguments the fixer will give to read, mocking it is not easy. I'll have to go with when(bitReader.read(anyInt())).thenAnswer(...) approach, implementing a custom answer that will create a lot of bit-fiddling logic to spoon-feed the object under test with proper bits in chunks of whatever size it asks for. Considering that bit streams I'm working with have rather complicated higher-level structure, it's not easy. And introducing logic in unit tests also doesn't smell good.

What do you think, is there any other option? Or maybe one of these can be improved in a way I fail to notice?

MassTransit consumer hard to test

I am having 2 issues testing MassTransit consumers:

  1. Sync issue
  2. MessageData

The first one is like this:

var testConsumer = TestFactory.ForConsumer<ImageUploadConsumer>().New(
                test =>
                {
                    test.UseConsumerFactory(new InstanceConsumerFactory<ImageUploadConsumer>(ImageConsumer));                    
                    test.Publish(message, (scenario, context) =>
                    {

                    });                    
                });

            testConsumer.Execute(); //Is non blocking

The following line (below) fails, because this line:

        moqFileMetaRepo.Verify(_ => _.Add(It.IsAny<IFileMeta>()),Times.Once ); 

is executed 9.9/10 before... this line ever did:

    public async Task Consume(ConsumeContext<ImageUploadWithThumb> context)

My fix has been to do

moqFileMetaRepo
            .Setup(repo => repo.Add(It.IsAny<IFileMeta>()))
            .Callback(() => { AutoEvent.Set(); });

And call the following before the assert:

AutoEvent.WaitOne(TimeSpan.FromSeconds(10));

Which is really a lot of work. And makes TDD or Testing in general a hassle, which I fear is only going to get ignored over time.

MessageData issue is another one. Here's the payload I'm sending through

        message = new ImageUploadWithThumb()
        {
            Id = Guid.NewGuid(),
            FileName = "Test.jpg",
            User = "Me",
            Extension = "jpg",
            OriginalImage = new ConstantMessageData<byte[]>(new Uri("https://g00gle.com"), new byte[] { 1, 2, 3 })
        };

I'm expecting to get byte[] { 1, 2, 3 } on the other end without having to resort to creating an actual persistence.

Instead: Got an error

On the sender side the MessageData.Value resolves ok. The consumer totally bombs. Works in prod though =_= which is not where testing should be.

I really just want to mock and UnitTest my consumer w/o having to wrestle with the framework - preferably in under 5 mins or so. Is there a way out while sticking to MT3?

Adding tests while refactoring in test driven development

Let's say that I am refactoring some classes that have unit tests already written. Let's assume that the test coverage is reasonable in the sense that it covers most use cases.

While refactoring I change some implementations. Move some variables, add/remove a few, abstract out things into some functions etc. The api of the classes and it's function has remained the same though.

Should I be adding tests when I am refactoring these classes? Or should I add a new test for every bit of refactoring? This is what I usually do when I am building up code rather than refactoring.

PS: Apologies if this is really vague.

Why are messages sent to trace source missing from all but the first unit test?

I observe a weird behavior with Visual Studio Enterprise 2015 Update 1. When using logging through .NET Framework TraceSource inside the unit tests, only the first unit test contains the logging output.

This is the way to reproduce the issue:

An empty unit test project contains the UnitTest1 class which looks like this:

using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class UnitTest1
{
    private readonly TraceSource trace = new TraceSource("Demo", SourceLevels.All);

    [TestMethod]
    public void TestMethod1()
    {
        this.trace.TraceEvent(TraceEventType.Information, 0, "Test 1 (trace source)");
        Console.WriteLine("Test 1 (console)");
    }

    [TestMethod]
    public void TestMethod2()
    {
        this.trace.TraceEvent(TraceEventType.Information, 0, "Test 2 (trace source)");
        Console.WriteLine("Test 2 (console)");
    }
}

The App.config file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="Demo" switchValue="Critical, Error, Warning, ActivityTracing, Information, Verbose">
        <listeners>
          <add name="ConsoleTraceListener" />
          <add name="TextFileListener" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="ConsoleTraceListener" type="System.Diagnostics.ConsoleTraceListener" />
      <add name="TextFileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="tests.log" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

When running the tests from Visual Studio:

  • The output of the first unit test is:

    Test Name:  TestMethod1
    Test Outcome:   Passed
    Result StandardOutput:  
    Demo Information: 0 : Test 1 (trace source)
    Test 1 (console)
    
    

    Both the messages from trace source and console are shown.

  • The output of the second unit test is:

    Test Name:  TestMethod2
    Test Outcome:   Passed
    Result StandardOutput:  Test 2 (console)
    
    

    While the output from Console.WriteLine works well, the one from TraceSource.TraceEvent is not shown.

Running the tests from the console by executing mstest /testcontainer:UnitTestProject1.dll reproduces the problem as well. The stdout reported for the first test contains two lines; the second test's stdout has one line only.

Why isn't logging traced for all but the very first test?

Can I change the input parameter value in a Moq.Callback() if it is a reference type?

I'm doing a unit test where the interesting part looks like this

_filter.Setup(x => x.Filter(It.IsNotNull<List<MyObject>>()))
            .Callback<List<MyObject>>(input => 
            {
                // input has two items while filteredObjects have one item.
                input = filteredObjects;
            });

The code

List<MyObject> myObjects = _repo.GetTheUnfilteredObjects(); // returns two items

// void
_filter.Filter(myObjects); 
// still two items

When I debug the test I can step into the moq callback method and see that it sets the input parameter to the new value (in this case a list of one item instead of two items as it was before). When I step on and looks in the method I test the property myObjects hasn't changed, it's still two items.

The question is, is it possible for me to set the parameter's value inside the callback method since it is a reference type? Thanks!

mercredi 30 mars 2016

How to use XUnit with Visual studio to unit test code running in a remote process

We are writing plugins for the Solidworks CAD system. Writing an addin involves compiling a DLL, registering it and then starting solidworks. Code in the dll can be configured to execute as soon as solidworks starts.

What I would like to do is craft a special DLL so that it runs a series of unit tests or a single unit test from visual studio and reports the results back to visual studio in the standard way.

We are happy to use either the standard visual studio test or resharper test system.

Is it possible to write an extension to the unit test system to achieve this. If so how difficult is this to achieve. Perhaps there are extensions that already do something similar for other plugin type environments that need testing.

Testing Prism event subscription and unsubscription count in Nsubstitute

I have few events that derive from a base class. I want to write a unit test that will verify that all the events were unsubscribed when navigating away from the page. As every event is a different derive type, Is there a way to use the base class to get the number of calls?

Class code 
private void SubscribeToEvent()
    {
        EventAggregator.GetEvent<RepositoryObjectAdded>().Subscribe(HandleTestGroupNodeAdded, ThreadOption.UIThread);
        EventAggregator.GetEvent<RepositoryObjectRemoved>().Subscribe(HandleTestNodeDeleted, ThreadOption.UIThread);
    }

private void UnsubscribeEvents()
    {
        EventAggregator.GetEvent<RepositoryObjectAdded>().Unsubscribe(HandleTestGroupNodeAdded);
        EventAggregator.GetEvent<RepositoryObjectRemoved>().Unsubscribe(HandleTestNodeDeleted);

    }

Test Class Code:
    [Fact]
    public void OnNavigatedFrom_UnsubscriptionCount()
    {
        NavigationContext navigationContext = Substitute.For<NavigationContext>(null, null);
        target.OnNavigatedFrom(navigationContext);
        CtorParams.EventAggregator.Received(EventSubscriptionCount).GetEvent<PubSubEvent<IUniqueObject>>().Unsubscribe(Arg.Any<Action<IUniqueObject>>());
    }

public class RepositoryObjectAdded : PubSubEvent<IUniqueObject>
{ 
}

public class RepositoryObjectRemoved : PubSubEvent<IUniqueObject>
{ 
}

error C2352 illegal call of non-static member function

I am creating a Heap type priority queue using a dynamically sized array. I am aware that vectors would be simpler to implement, but this is a learning exercise for me. Everything works great, but I am having issues only when attempting some Unit testing in visual studio '13. I'm experiencing this error

Here is the source file where I attempt to run the Unit tests:

//Prog1Test.cpp
#include "UnitTest.h"
#include <iostream>

int main()
{
    PriorityQueue Q = PriorityQueue();
    UnitTest::test1(Q);
    UnitTest::test2(Q);
    UnitTest::test3(Q);
    UnitTest::test4(Q);
    return 0;
}

Here is the UnitTest.cpp:

//UnitTest.cpp
#include "UnitTest.h"
#include <cassert>

void UnitTest::test1(PriorityQueue Q)
{
    Q.clear();
    Q.append('a');
    Q.append('b');
    assert(Q.size() == 2);
    assert(Q.check() == true);
}

void UnitTest::test2(PriorityQueue Q)
{
    Q.clear();
    Q.append('b');
    Q.append('a');
    assert(Q.size() == 2);
    assert(Q.check() == false);
}

void UnitTest::test3(PriorityQueue Q)
{
    Q.clear();
    Q.insert('a');
    Q.insert('b');
    assert(Q.size() == 2);
    assert(Q.check() == true);
    assert(Q.remove() == 'a');
    assert(Q.size() == 1);
}

void UnitTest::test4(PriorityQueue Q)
{
    Q.clear();
    Q.insert('b');
    Q.insert('a');
    assert(Q.size() == 2);
    assert(Q.check() == true);
    assert(Q.remove() == 'a');
    assert(Q.size() == 1);
}

Here is the UnitTest header file:

//UnitTest.h
#ifndef UnitTest_H
#define UnitTest_H
#include "PriorityQueue.h"

class UnitTest
{
public:
    void test1(PriorityQueue Q);
    void test2(PriorityQueue Q);
    void test3(PriorityQueue Q);
    void test4(PriorityQueue Q);
};


#endif

Here is the PriorityQueue class header:

#ifndef PriorityQueue_H
#define PriorityQueue_H

class PriorityQueue
{
private:
    char *pq;
    int length;
    int nextIndex;
    char root;
public:
    PriorityQueue();
    ~PriorityQueue();
    char& operator[](int index);
    void append(char val);
    int size();
    void clear();
    void heapify();
    bool check();
    void insert(char val);
    char remove();
    friend class UnitTest;
};


#endif

here is the priorityqueue.cpp file:

#include<math.h>
#include "PriorityQueue.h"




PriorityQueue::PriorityQueue()
{
    pq = new char[0];
    this->length = 0;
    this->nextIndex = 0;
}




PriorityQueue::~PriorityQueue() {
    delete[] pq;
}




char& PriorityQueue::operator[](int index) {
    char *pnewa;
    if (index >= this->length) {
        pnewa = new char[index + 1];
        for (int i = 0; i < this->nextIndex; i++)
            pnewa[i] = pq[i];
        for (int j = this->nextIndex; j < index + 1; j++)
            pnewa[j] = 0;
        this->length = index + 1;
        delete[] pq;
        pq = pnewa;
    }
    if (index > this->nextIndex)
        this->nextIndex = index + 1;
    return *(pq + index);
}




void PriorityQueue::append(char val) {
    char *pnewa;
    if (this->nextIndex == this->length) {
        this->length = this->length + 1;
        pnewa = new char[this->length];
        for (int i = 0; i < this->nextIndex; i++)
            pnewa[i] = pq[i];
        for (int j = this->nextIndex; j < this->length; j++)
            pnewa[j] = 0;
        delete[] pq;
        pq = pnewa;
    }
    pq[this->nextIndex++] = val;
}



int PriorityQueue::size() {
    return this->length;
}




void PriorityQueue::clear() {
    delete[] pq;
    pq = new char[0];
    this->length = 0;
    this->nextIndex = 0;
}




void PriorityQueue::heapify() {
    char parent;
    char root;
    char temp;
    for (double i = this->length - 1; i >= 0; i--)
    {
        root = pq[0];
        int parentindex = floor((i - 1) / 2);
        int leftchildindex = 2 * i + 1;
        int rightchildindex = 2 * i + 2;
        if (pq[(int)i] <= pq[leftchildindex] && pq[(int)i] <= pq[rightchildindex])
        {
            pq[(int)i] = pq[(int)i];
        }
        else if (rightchildindex < this->length && pq[(int)i] > pq[rightchildindex])
        {
            temp = pq[(int)i];
            pq[(int)i] = pq[rightchildindex];
            pq[rightchildindex] = temp;
            heapify();
        }
        else if (leftchildindex < this->length && pq[(int)i] > pq[leftchildindex])
        {
            temp = pq[(int)i];
            pq[(int)i] = pq[leftchildindex];
            pq[leftchildindex] = temp;
            heapify();
        }
    }
}



void PriorityQueue::insert(char val) {
    char *pnewa;
    if (this->nextIndex == this->length) {
        this->length = this->length + 1;
        pnewa = new char[this->length];
        for (int i = 0; i < this->nextIndex; i++)
            pnewa[i] = pq[i];
        for (int j = this->nextIndex; j < this->length; j++)
            pnewa[j] = 0;
        delete[] pq;
        pq = pnewa;
    }
    pq[this->nextIndex++] = val;
    PriorityQueue::heapify();
}


bool PriorityQueue::check() {
    char root;
    root = pq[0];
    for (int i = this->length - 1; i >= 0; i--)
    {
        if ((int)pq[i]< (int)root)
            return false;
    }
    return true;
}



char PriorityQueue::remove() {
    char root = pq[0];
    char *qminus;
    qminus = new char[this->length];
    for (int i = 1; i<this->length; i++)
        qminus[i - 1] = pq[i];
    pq = qminus;
    this->length -= 1;
    PriorityQueue::heapify();
    return root;
}

How to pretty format ansi characters in mocha console [0m xyz←[0m

I'm following this tutorial frontend-testing-with-phantomjs-casperjs-mocha-and-chai so that I can use mocha, chai, casperjs and phantomjs.

I can get code working, but I don't really understand how to format output so that it is readable.

I believe I may need to setup a mocha reporter, but I'm not quite sure if this is correct or how to go about it.

The output looks like this

←[0m←[0m
←[0m  xyz←[0m
111111111
←[2K←[0G  ←[32m  Ô£ô←[0m←[90m should dosomething←[0m
222222222222
←[2K←[0G  ←[32m  Ô£ô←[0m←[90m should dosomething else←[0m

Output

main.js

var config = require('./config');
var chai = require('chai');
var expect = chai.expect;
var code1 = require('./code1');
var Mocha = require('mocha');

var mocha = new Mocha({
  reporter: 'list'
});
//mocha.reporter('list').run();

describe('Home page', function () {
  before(function() {
    casper.start('http://ift.tt/YV9WJO');
  });

  it('should dosomething', function (done) {
    console.log('xxxxxxxxxx');
    done();
  });

  code1.go();
});

code1.js

module.exports = {
  go: describe('xyz', function() {

    it('should dos omething', function(done) {
      console.log('111111111');
      done();
    });

    it('should do something else', function (done) {
      console.log('222222222222');
      done();
    });
  })

};

PowerMock mockStatic not mocking the class

I have the following class(and method in it)

class Fetcher{

 public void fetch(String key){
      File file = File.createTempFile(key,"*.txt");
      ..... 
      ....
 } 

}

I want to unit test this method and want to mock the createTempFile method For this i have written the unit test as follows

@RunWith(PowerRunner.class)

@PrepareForTest({File.class})

public class FetcherTest {

public void test() {
 String key = "key";
 File file = new File("Hello");
 PowerMock.mockStatic(File.class);
 EasyMock.expect(File.createTempFile(EasyMock.anyObject(String.class),EasyMock.anyObject(String.class))).andReturn(file).once();
 PowerMock.replay(File.class);
 Fetcher fetcher = new Fetcher();
 fetcher.fetch("key");
 PowerMock.verify(File.class);

} }

Executing the unit test provides the following error:

Expectation failure on verify: File.createTempFile(,): expected: 1,actual: 0

I have looked through a lot of articles but am not able to figure out what's missing here and why File is not getting mocked. Please help with any suggestions

Pass date testing angular unit tests

I have a ternary that seems to be returning a passing test, but it is failing.

$scope.depart = (typeof serverShortDate !== 'undefined') ? new Date(serverShortDate) : new Date();



AssertionError: expected Wed, 30 Mar 2016 21:26:12 GMT to deeply equal Wed, 30 Mar 2016 21:26:12 GMT

Here is my simple spec

    expect(scope.depart).to.deep.equal(new Date());

All that I can imagine is that somewhere is a difference. The error message shows the same values.

Xunit multiple IClassFixtures

My question is How to setup multiple fixtures in one test class?

But the constructor of Zoo class can not handle multiple fixtures.

For exemple:

public class Zoo : IClassFixture<Tiger>, IClassFixture<Wolf>, IClassFixure<Bird>
{
   private IFixture fixture;
   public Zoo(IFixture fixture) 
   { 
    this.fixture = fixture; 
   }

   [Fact]
   public void TestAnimal()
   {
    //Arrange 
    int actualBonesCount = this.fixture.BonesCount;
    int expectedBonesCount = 2;

    //Act & Assert
    Assert.Equal(expectedBonesCount, actualBonesCount );
   }
} 

A tiger class

public class Tiger : FixtureBase
{
   public Tiger()
   {
    this.BonesCount  = 4;
   }
}

A bird class

public class Bird: FixtureBase
{
   public Bird()
   {
    this.BonesCount  = 2;
   }
}

Test fixture base class

public class FixtureBase : IFixture
{
   public int BonesCount { get; set; }
}

And interface

public interface IFixture
{
   int BonesCount { get; set; }
}

How can I send a null request for my unit test using Microsoft.Owin.Testing?

Where I'm grabbing the response, I'm trying to figure out a way to send a null request to test a condition in my Invoke statement. I can't figure out how to do that using MicroSoft.Owin.Testing.

// from the test
using (var server = TestServer.Create(app => {
    var mw = new myMiddleware(_fakeMiddleware, _fakeCacheService, _fakeConfigHelper);
    app.UseMyMiddleWare(resolver);
    app.Run(async context => {
        await mw.Invoke(context);
    });
})) {
        // this is the sore spot
        var response = server.CreateRequest("").GetAsync();

        Assert.AreEqual(response.Result.StatusCode, HttpStatusCode.BadRequest);
}

    // from the middle ware
    if (context.Request == null) {
        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return; //Stop pipeline
    }

I put Microsoft.Owin.Testing in the title since it wasn't a tag.

AngularJS unit test Directive's attribute value

I have a directive that looks like this:

<foo bar="5"></foo>

where bar is an attribute and not defined in the scope property of the DDO. How can I write a unit test to assert that the value of bar is 5?

Excluding configuration in test classes from @ComponentScan

I've been running into @ComponentScan issues with @Configuration classes for tests -- namely, the @ComponentScan is pulling in unintended @Configuration during integration tests.

For example, say you've got some global config in src/main/java which pulls in components within com.example.service, com.example.config.GlobalConfiguration:

package com.example.config;
...
@Configuration
@ComponentScan(basePackageClasses = ServiceA.class)
public class GlobalConfiguration {
    ...
}

It's intended to pull in two services, com.example.services.ServiceA and com.example.services.ServiceB, annotated with @Component and @Profile("!test") (omitted for brevity).

Then in src/test/java, com.example.services.ServiceATest:

package com.example.services;
...
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ServiceATest.ServiceATestConfiguration.class)
public class ServiceATest {
    ...
    @Configuration
    public static class ServiceATestConfiguration {
         @Bean
         public ServiceA serviceA() {
             return ServiceA(somemocking...);
         }
    }
}

And also com.example.ServiceBIntegrationTest, which needs to pull in GlobalConfiguration.class in order to be an integration test, but still avoids pulling in dangerous implementations with @ActiveProfiles("test"):

package com.example.services;
...
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = {GlobalConfiguration.class, ServiceBIntegrationTest.ServiceBIntegrationTestConfiguration.class})
public class ServiceBIntegrationTest {
    ...
    @Configuration
    public static class ServiceBIntegrationTestConfiguration {
         @Bean
         public ServiceB serviceB() {
             return ServiceB(somemocking...);
         }
    }
}

The obvious intention of the ServiceBIntegrationTest is to pull in the complete src/main/java application configuration via GlobalConfiguration, exclude dangerous components via @ActiveProfiles("test") and replace those excluded components with its own implementations. However, during tests the namespace of src/main/java and src/test/java are combined, so GlobalConfiguration's @ComponentScan finds more in the classpath than it normally would -- namely, the ServiceA bean defined in ServiceA.ServiceATestConfiguration. That could easily lead to conflicts and unintended results.

Now, you could do something on GlobalConfiguration like @ComponentScan(..., excludeFilters= @ComponentScan.Filter(type = FilterType.REGEX, pattern = "\\.*(T|t)est\\.*")), but that has issues of its own. Relying on naming conventions is pretty brittle; still, even if you backed out a @TestConfiguration annotation and used FilterType.ANNOTATION, you'd effectively be making your src/main/java aware of your src/test/java, which it shouldn't be, IMO (see note below).

As it stands, I've solved my problem by using an additional profile. On ServiceA, I add a unique profile name -- so that its profile annotation becomes something like @ActiveProfiles("test,serviceatest"). Then, on ServiceATest.ServiceATestConfiguration I add the annotation @Profile("serviceatest"). This effectively limits the scope of ServiceATestConfiguration with relatively little overhead, but it seems like either:

a) I am using @ComponentScan incorrectly, or

b) There should be a much cleaner pattern for handling this problem

Which is it?


note: yes, the app is test-aware because it's using @Profile("!test"), but I'd argue making the application slightly test-aware to defend against improper resource usage and making it test-aware to ensure correctness of tests are very different things.

PYTHON: nosetests import file path with multiple modules/files

I'm currently working through LearnPythonTheHardWay and have reached Exercise 48 which details Nosetests. I am able to perform a unit testing as long as all of the code is in a single python.py file. However if I include other files as part of a program, i.e. use import and then attempt to nosetest such a project I am getting an error, as follows:

======================================================================

ERROR: Failure: ImportError (No module named 'temp')

Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/usr/local/lib/python3.4/dist-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python3.4/dist-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python3.4/dist-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/usr/lib/python3.4/imp.py", line 235, in load_module
return load_source(name, filename, file)
File "/usr/lib/python3.4/imp.py", line 171, in load_source
module = methods.load()
File "", line 1220, in load
File "", line 1200, in _load_unlocked
File "", line 1129, in _exec
File "", line 1471, in exec_module
File "", line 321, in _call_with_frames_removed
File "/home/userjeeves/LEARNPYTHONTHEHARDWAY/ex48/tests/scanner_tests.py", line 6, in
from ex48.scanner import lexicon
File "/home/userjeeves/LEARNPYTHONTHEHARDWAY/ex48/ex48/scanner.py", line 6, in
import temp
ImportError: No module named 'temp'


Ran 1 test in 0.028s

FAILED (errors=1)

The structure of my project directories are as follows:

ex48/
  ex48/
     scanner.py
     temp.py
  __pycache__/
  tests/
     __init__.py
    scanner_tests.py

My scanner_tests.py file is as follows:

from nose.tools import *
from ex48.scanner import lexicon
from ex48 import temp

def test_directions():
    assert_equal(lexicon.scan("north"),[('direction','north')])
        result = lexicon.scan("north south east")
        assert_equal(result, [('direction', 'north'),
                          ('direction', 'south'),
                          ('direction', 'east')])

My scanner.py file is as follows:

   import temp

   class lexicon:
       def scan(val):
          if(val == "north"):
              return [('direction', 'north')]
          else:
              return [('direction', 'north'),
                      ('direction', 'south'),
                      ('direction', 'east')]

    runner = temp.temp("hello")

And finally my temp.py file is as follows:

   class temp(object):
       def __init__(self,name):
           self.name = name
       def run(self):
           print "Your name is; %s" % self.name     
    runner.run()

My question is how to overcome the ImportError: No Module named 'temp' because it seems as if I have imported the temp.py file in both the scanner.py file and the scanner_tests.py file but nose does not seem to be able to import it when it runs. Nosetests works fine when its just the single scanner.py file but not when importing. Is there a special syntax for importing into a unit test for nose? The script also works fine when run and imports properly at the command line.

*Note: I'm running python off a limited account off an online server so some admin privileges are not available.

Unit testing in AngularJS with Jasmine and Chutzpah

I am trying to write Unit test cases for existing SPA project built on angularJS. I get the "Can't find variable: module" error whenever I try to execute the code.

I installed the libraries using npm.

I used Chutzpah and Jasmine libraries for this.

appController.js:

(function () {
'use strict';

  angular
      .module('app', [])
      .controller('appController', appController);

  appController.$inject = ['apiServices', '$scope'];

  function appController(apiServices, $scope) {
    $scope.value = 5;
  }
})();

apiServices.js

(function () {
'use strict';

  angular
      .module('app',[])
      .factory('apiServices', apiServices);

  apiServices.$inject = ['$http', '$log', '$q'];

  function apiServices($http, $log, $q) {
    var clientServicesPath = '/api/ClientServices',
    service =
       {  .......  };

    return service;
  }
})();

appControllerSpec.js

/// <reference path="../../../lib/angular/angular.js" />
/// <reference path="../../services/apiservices.js" />
/// <reference path="../../controllers/appcontroller.js" />
/// <reference path="../../../../node_modules/jasmine/bin/jasmine.js" />
/// <reference path="../../../../node_modules/jasmine/lib/jasmine.js" />
/// <reference path="../../../../node_modules/jasmine-ajax/lib/mock-ajax.js" />
/// <reference path="../../../lib/angular-mocks/angular-mocks.js" />

describe('When using appController ', function () {
  //initialize Angular
  beforeEach(module('app'));   
  var ctrl, scope, apiServices;

  beforeEach(inject(function ($injector) {
    apiServices = $injector.get('apiServices');
  }));

  beforeEach(inject(function ($controller, $rootScope, apiServices) {
    scope = $rootScope.$new();
    var ctrl = $controller('appController', { $scope: scope, apiServices: apiServices });
  }));

  it('initial value is 5', function () {
    expect(scope.value).toBe(5);
  });
});

I always get the following error:

Test 'When using appController :initial value is 5' failed Error: [$injector:unpr] Unknown provider: apiServicesProvider <- apiServices http://ift.tt/1Tj7CdW$injector/unpr?p0=apiServicesProvider%20%3C-%20apiServices (line 4418) at getService (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4571:46) at file:///C:/Users/Bhanu/......./lib/angular/angular.js:4423:48 at getService (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4571:46) at file:///C:/Users/Bhanu/......./js/TestingJS/controllers/appControllerSpec.js:16:36 at invoke (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4625:24) Error: [$injector:unpr] Unknown provider: apiServicesProvider <- apiServices http://ift.tt/1Tj7CdW$injector/unpr?p0=apiServicesProvider%20%3C-%20apiServices (line 4418) at getService (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4571:46) at file:///C:/Users/Bhanu/......./lib/angular/angular.js:4423:48 at getService (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4571:46) at injectionArgs (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4595:68) at invoke (file:///C:/Users/Bhanu/......./lib/angular/angular.js:4617:31) TypeError: undefined is not an object (evaluating 'scope.value') in file:///C:/Users/Bhanu/......./js/TestingJS/controllers/appControllerSpec.js (line 25) at attemptSync (file:///C:/Users/Bhanu/AppData/Local/Microsoft/VisualStudio/14.0/Extensions/3nmdcohr.lvt/TestFiles/jasmine/v2/jasmine.js:1886:28) at run (file:///C:/Users/Bhanu/AppData/Local/Microsoft/VisualStudio/14.0/Extensions/3nmdcohr.lvt/TestFiles/jasmine/v2/jasmine.js:1874:20) at execute (file:///C:/Users/Bhanu/AppData/Local/Microsoft/VisualStudio/14.0/Extensions/3nmdcohr.lvt/TestFiles/jasmine/v2/jasmine.js:1859:13) at queueRunnerFactory (file:///C:/Users/Bhanu/AppData/Local/Microsoft/VisualStudio/14.0/Extensions/3nmdcohr.lvt/TestFiles/jasmine/v2/jasmine.js:697:42) at execute (file:///C:/Users/Bhanu/AppData/Local/Microsoft/VisualStudio/14.0/Extensions/3nmdcohr.lvt/TestFiles/jasmine/v2/jasmine.js:359:28) in C:\Users\Bhanu.......\js\TestingJS\controllers\appControllerSpec.js (line 24)

I have tried all the possible solutions but none worked for me. I ran the tests directly by right clicking the Test controller file and selecting the option "Run JS Tests".

It works fine if I remove the service injection both from controller and test.

I feel there are more pieces towards configuration. Please help me with this.

1205 Lock wait timeout exceeded while unit testing with database transactions

I am doing some unit testing using phpunit. When I run the tests it hangs fora while, then I get an error:

SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction (SQL: update booking_product set klarna_invoiceId = 7777, klarna_product_status = 3, updated_at = 2016-03-30 18:43:43 where booking_id = 8 and product_id = 1)

If I don't use database transactions I don't have this problem. Some of the tests are working on the same database record.

I'm sure I'm doing sometihng wrong, how do I resolve this issue?

Any way to mock Files.write(...) method?

I need help with the unit test case. I want to mock static method write(Path path, byte[] bytes, OpenOption... options) of java.nio.file.Files class.

I tried eg. in that way:

PowerMockito.doReturn(path).when(Files.class, "write", path, someString.getBytes());

In this case the method is not found.

PowerMockito.doReturn(path).when(Files.class, PowerMockito.method(Files.class, "write", Path.class, byte[]
            .class, OpenOption.class));

This time i have UnfinishedStubbingException.

How can I do it correct?

Correct way of unit-testing classes that use DateTimeOffset objects?

I would appreciate information or examples about how to correctly test code that uses DateTimeOffset instances. I know the tests have to be deterministic.

So, how would one isolate the application from the DateTimeOffset classes ? I would, of course, like to be able to use a fake DateTimeOffset.Now, etc.

In my tests, should I be using something like: var myDate = new DateTimeOffset(2016, 3, 29, 12, 20, 35, 93, TimeSpan.FromHours(-3));

Or would I instead be using a wrapper class like MyCustomDateTimeOffset ? Should I not use DateTimeOffset at all in my code and use a wrapper instead?

Why do Angular unit tests load $route?

After updating to Angular 1.5.3 (from 1.4.9) all my unit tests have started failing, where they worked before.

The error is as follows:

Error: [$injector:unpr] Unknown provider: 
       AuthenticationHttpInterceptorProvider
         <- AuthenticationHttpInterceptor
           <- $http
             <- $templateRequest
               <- $route

It is expected that the AuthenticationHttpInterceptorProvider is not known at this point, because it is part of a different module which is not unit tested here. If I provide a mock for this interceptor, I get the error that $httpBackend wasn't expecting a GET request for the defined default route.

My question is: Why does $route get loaded in the first place, and how can I prevent it? I'm not unit testing any routes and make no changes to $route after the .config stage in the app where routes are defined. I would expect to never receive any requests for the templateUrls of the views of routes.

I've not been able to find anything in the Angular Changelog that would make me expect a different behaviour with the newer version.

How to make unit test fail when API of mocked module changed

When I write some javascript unit tests for my code, I mocked a methond of a module with sinon, defined what arguments it expected and what it should return.

someone changed the argument of that method and he forgot to change my code. now my code were broken, but the unit tests still passed because I used the mocked module in the unit tests.

how to make unit tests fail when mocked module changed, so that this issue could be exposed?

Thanks!

Angular $httpBackend how to mock an error response?

I'm trying to test that my program processes the error messages I get from http requests properly, but I can't figure out how to mock that with $httpBackend. Given the following:

$httpBackend.expectGET(path).respond(400, object);

400 sets response.status, and object sets response.data, but how do I set response.error? The data I need to test isn't in the data field.

No transactionManager error in Grails 3 Integration test

I have created a new Grails 3.1.4 angular project along with a few domain objects and controllers extending RestfulController. I have created the Integration test below. When I run grails test-app -integration I get the error

java.lang.IllegalStateException: No transactionManager was specified. Using @Transactional or @Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.
    at grails.transaction.GrailsTransactionTemplate.<init>(GrailsTransactionTemplate.groovy:60)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.$tt__$spock_feature_0_0(BillingEntityRestControllerIntegrationSpec.groovy:29)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities_closure2(BillingEntityRestControllerIntegrationSpec.groovy)
    at groovy.lang.Closure.call(Closure.java:426)
    at groovy.lang.Closure.call(Closure.java:442)
    at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
    at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
    at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities(BillingEntityRestControllerIntegrationSpec.groovy)

Test class:

package com.waldoware.invoicer

import grails.test.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*

@Integration
@Rollback
class BillingEntityRestControllerIntegrationSpec extends Specification {

    def setupData() {
        def biller = new BillingEntity()
        biller.with {
            companyName = "Acme, Inc."
        }
        def ledger = new Ledger(name: "My Ledger", billingEntity: biller).save(failOnError: true, flush: true)
    }

    void 'test all entities'() {
        when:
        setupData()
        new BillingEntityRestController().index()

        then:
        response.contentType == 'application/json;charset=UTF-8'
        response.status == HttpServletResponse.SC_OK
        response.text == "[{}]"
    }
}

Unit testing an object in Perl. Checking that it contains specific hash values

I have created an error object from an error hash and I'm trying to create unit tests that check the objects contain all the correct keys.

ErrorLibrary.pm

use constant {

    CABLING_ERROR => {
    errorCode => 561,
    message => "cabling is not correct at T1",
    tt => { template => 'disabled'},
    fatal => 1,
    link =>'http://ift.tt/231CJxl',
    },
};

Error.pm - new subroutine. (Takes error hash as arg & creates a new error object)

package ASC::Builder:Error;
sub new {

    my ($package, $first_param) = (shift, shift);


    if (ref $first_param eq 'HASH') {
        my %params = @_;
        return bless { message => $first_param->{message}, %params}, $package;
    }
    else {
        my %params = @_; 
        return bless {message => $first_param, %params}, $package;

}   
}

I'm not sure what I should be testing as my expected output. The specific message key in the hash or an Error object itself. I've been trying to test if a certain key of the hash is contained in the error object, but I don't think I'm going about it the right way. Anyway here is what I've been messing around with:

error_test.t

my $error = CABLING_ERROR;
#is(ref $error, 'HASH', 'error is a hashref');


my $error_in = ASC::Builder::Error->new($error);

my $exp_out_A = ($error->{message}); # is this the right expected output????

is(ref $error_in eq ASC::Builder::Error, 'It is an Error object'); #seen something like this online

#is(defined $error->{errorCode}, 1, "Error object contains key errorCode"); #these only test that the error hash contains these keys
#is(defined $error->{message}, 1, "Error object contains key message");


is($error_in, $exp_out_A, 'Correct message output');

The test file is a bit messy, just because I've been trying various attempts. I hope all the code is free of syntax errors :). Any help would be much appreciated!