vendredi 31 juillet 2015

Jest(react testing tool) error - Parse Error: Line 1: Illegal import declaration

I'm now using node.js(0.10.x) version, jest(0.4.x) version to test react.js.

Before I decided to test my react components, I have used node.js 0.12.x version. Change through nvm to 0.10.x.

I rebuilded the all the modules and restarted the test.

The error is below.

Using Jest CLI v0.4.17
 PASS  __tests__/unit/app.test.js (0.058s)
 PASS  __tests__/unit/preprocessor.js (0.68s)
 FAIL  __tests__/unit/mypage.test.js
Error: /Users/nuko/WebstormProjects/pliky/__tests__/unit/mypage.test.js: /Users/nuko/WebstormProjects/pliky/__tests__/unit/preprocessor.js: Parse Error: Line 1: Illegal import declaration
  at throwError (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2813:21)
  at throwErrorTolerant (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2825:24)
  at parseSourceElement (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:6390:17)
  at parseProgramElement (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:6446:16)
  at parseProgramElements (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:6478:29)
  at parseProgram (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:6491:16)
  at Object.parse (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/node_modules/esprima-fb/esprima.js:7653:23)
  at getAstForSource (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/src/jstransform.js:251:21)
  at transform (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/node_modules/jstransform/src/jstransform.js:274:11)
  at innerTransform (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/main.js:94:10)
  at Object.module.exports.transform (/Users/nuko/WebstormProjects/pliky/node_modules/react-tools/main.js:20:18)
  at Object.module.exports.process (/Users/nuko/WebstormProjects/pliky/__tests__/unit/preprocessor.js:5:27)
  at Object.readAndPreprocessFileContent (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/lib/utils.js:432:33)
  at Loader._execModule (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:209:11)
  at Loader.requireModule (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:914:12)
  at Loader.requireModuleOrMock (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:935:17)
  at /Users/nuko/WebstormProjects/pliky/__tests__/unit/mypage.test.js:4:14
  at Object.runContentWithLocalBindings (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/lib/utils.js:485:17)
  at Loader._execModule (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:245:9)
  at Loader.requireModule (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:914:12)
  at jasmineTestRunner (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/jasmineTestRunner/jasmineTestRunner.js:292:16)
  at /Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/src/TestRunner.js:376:12
  at tryCatcher (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/util.js:26:23)
  at Promise._settlePromiseFromHandler (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/promise.js:503:31)
  at Promise._settlePromiseAt (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/promise.js:577:18)
  at Promise._settlePromises (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/promise.js:693:14)
  at Async._drainQueue (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/async.js:123:16)
  at Async._drainQueues (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/async.js:133:10)
  at Async.drainQueues (/Users/nuko/WebstormProjects/pliky/node_modules/jest-cli/node_modules/bluebird/js/main/async.js:15:14)
  at process._tickCallback (node.js:448:13)

1 test failed, 2 tests passed (3 total)
Run time: 2.189s
npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0

My preprocessor.js code.(same as the official document script)

    var ReactTools = require('react-tools');

    module.exports = {
        process: function(src) {
            return ReactTools.transform(src);
        }
    };

My mypage.test.js code.

jest.dontMock('../../React/mypage.js');

var React = require('react/addons'),
    Mypage = require('../../React/mypage.js'),
    TestUtils = React.addons.TestUtils;

describe('mypage', function() {

    var MypageElement = TestUtils.renderIntoDocument(<Mypage />);

    var list = TestUtils.scryRenderedDOMComponentsWithTag(MypageElement, 'option');


    it('has 3 default items', function() {
        expect(list.props.children.length).toEqual(5);
    });
});

And I added this part to package.json file.

"jest": {
    "scriptPreprocessor": "./__tests__/unit/preprocessor.js",
    "unmockedModulePathPatterns": [
      "./node_modules/react"
    ]
  },

Where is this error come from and how can I fix this? Please let me know. Thank you.

AngularJS Unit Testing with Karma in WebStorm:- Chrome 43.0.2357 (Windows 7 0.0.0): Executed 0 of 0 ERROR

I am new to AngularJs Unit Testing. I am using WebStorm for testing my simple angularjs app. but it will show this error. i dont understand what to do.

my karma.conf.js

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

basePath : './',

files : [
  'app/bower_components/angular/angular.js',
  'app/bower_components/angular-route/angular-route.js',
  'app/bower_components/angular-mocks/angular-mocks.js',
  'app/components/**/*.js',
  'app/view*/**/*.js',
  'app/test/*.js'
],

autoWatch : true,

frameworks: ['jasmine'],

browsers : ['Chrome'],

plugins : [
        'karma-chrome-launcher',
        'karma-firefox-launcher',
        'karma-jasmine',
        'karma-junit-reporter'
        ],

junitReporter : {
  outputFile: 'test_out/unit.xml',
  suite: 'unit'
}

}); };

my test.js:-

'use strict';

describe('myApp.view2 module', function() {

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

var $controller;

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

describe('PasswordCheckerController ', function(){

it('should be defined', inject(function($controller) {
  //spec body
  var view2Ctrl = $controller('PasswordCheckerController');
  expect(view2Ctrl).toBeDefined();
}));

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

}); });

Unit testing with robolectric gives NoSuchMethodException error

after some time of research I still haven't found out why this thing happens in my Android code. This is just standard simple unit test code, Not much is really going on. I tried this code previously on my work machine and successfully runs the unit test. I don't know why this happens at my other pc at home. Maybe it could be caused by some incorrect setup of robolectric 3, I'm not really sure. I attached the full log report maybe you guys will be able to understand it better. Thanks.

Gradle command to run unit test:

gradlew test

Error:

com.sample.bigger.MainActivityTest > sampleTest FAILED
java.lang.RuntimeException                              
    Caused by: java.lang.RuntimeException               
        Caused by: java.lang.NoSuchMethodException      

Full log:

java.lang.RuntimeException: java.lang.NoSuchMethodException: android.os.Looper.<init>(boolean)
    at org.robolectric.util.ReflectionHelpers.callConstructor(ReflectionHelpers.java:297)
    at org.robolectric.shadows.ShadowLooper.createLooper(ShadowLooper.java:43)
    at org.robolectric.shadows.ShadowLooper.access$000(ShadowLooper.java:25)
    at org.robolectric.shadows.ShadowLooper$1.create(ShadowLooper.java:37)
    at org.robolectric.shadows.ShadowLooper$1.create(ShadowLooper.java:35)
    at org.robolectric.util.SoftThreadLocal$1.initialValue(SoftThreadLocal.java:13)
    at org.robolectric.util.SoftThreadLocal$1.initialValue(SoftThreadLocal.java:11)
    at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:160)
    at java.lang.ThreadLocal.get(ThreadLocal.java:150)
    at org.robolectric.util.SoftThreadLocal.get(SoftThreadLocal.java:18)
    at org.robolectric.shadows.ShadowLooper.resetThreadLoopers(ShadowLooper.java:55)
    at org.robolectric.Shadows.reset(Shadows.java:1612)
    at org.robolectric.Robolectric.reset(Robolectric.java:22)
    at org.robolectric.internal.ParallelUniverse.resetStaticState(ParallelUniverse.java:43)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:233)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodException: android.os.Looper.<init>(boolean)
    at java.lang.Class.getConstructor0(Class.java:2892)
    at java.lang.Class.getDeclaredConstructor(Class.java:2058)
    at org.robolectric.util.ReflectionHelpers.callConstructor(ReflectionHelpers.java:283)
    ... 48 more

This is my mainActivityTest

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 18)
public class MainActivityTest {

@Test
    public void sampleTest(){
        Assert.assertEquals("hey", "hey");
    }
}

This is my build.gradle file

apply plugin: 'com.android.application'
android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.sample.bigger"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // Added for AdMob
    compile project(':jokeproviderlib')
    compile project(':jokedisplayer')
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.google.android.gms:play-services:7.3.0'
    compile project(path: ':jokeGCMbackend', configuration: 'android-endpoints')
    compile 'com.google.mockwebserver:mockwebserver:20130706'


    testCompile 'junit:junit:4.12'
    testCompile "org.mockito:mockito-core:1.9.5"
    testCompile('org.robolectric:robolectric:3.0') {
        exclude group: 'commons-logging', module: 'commons-logging'
        exclude group: 'org.apache.httpcomponents', module: 'httpclient'
    }
}

I have seen the following sources, the first seems to be the closest one. I'm still trying how to do it.

Kill process launched via thread

I have a headless application that uses sockets for communication. When launched, it remains active until sent a message telling it to quit (or it crashes, or is killed).

When unit testing this application using Ruby, I need to launch the process, interact with it (via sockets), and then kill it.

I thought I could do this using this pattern:

class TestServer < MiniTest::Unit::TestCase
  def setup
    @thread = Thread.new{ `#{MY_COMMAND}` }
  end

  def test_aaa
    # my test code
  end

  def teardown
    @thread.kill if @thread
  end
end

However, that teardown code kills the thread but does not kill the process launched by it.

How can I launch the process in a way that:

  1. Allows it to run in the background (immediately returns control to my Ruby test harness)
  2. Allows me to force kill the process later on, if need be.

I happen to be developing on OS X, but if possible I'd appreciate a generic solution that works across all OS where Ruby runs.

Code Coverage analysis shows 100% coverage when most of the class is missing coverage

I have a class that implements the IDisposable interface.

using System;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// <para>
/// The Engine Timer allows for starting a timer that will execute a callback at a given interval.
/// </para>
/// <para>
/// The timer may fire:
///  - infinitely at the given interval
///  - fire once
///  - fire _n_ number of times.
/// </para>
/// <para>
/// The Engine Timer will stop its self when it is disposed of.
/// </para>
/// <para>
/// The Timer requires you to provide it an instance that will have an operation performed against it.
/// The callback will be given the generic instance at each interval fired.
/// </para>
/// <para>
/// In the following example, the timer is given an instance of an IPlayer. 
/// It starts the timer off with a 30 second delay before firing the callback for the first time.
/// It tells the timer to fire every 60 seconds with 0 as the number of times to fire. When 0 is provided, it will run infinitely.
/// Lastly, it is given a callback, which will save the player every 60 seconds.
/// @code
/// var timer = new EngineTimer<IPlayer>(new DefaultPlayer());
/// timer.StartAsync(30000, 6000, 0, (player, timer) => player.Save());
/// @endcode
/// </para>
/// </summary>
/// <typeparam name="T">The type that will be provided when the timer callback is invoked.</typeparam>
public sealed class EngineTimer<T> : CancellationTokenSource, IDisposable
{
    /// <summary>
    /// The timer task
    /// </summary>
    private Task timerTask;

    /// <summary>
    /// How many times we have fired the timer thus far.
    /// </summary>
    private long fireCount = 0;

    /// <summary>
    /// Initializes a new instance of the <see cref="EngineTimer{T}"/> class.
    /// </summary>
    /// <param name="callback">The callback.</param>
    /// <param name="state">The state.</param>
    public EngineTimer(T state)
    {
        if (state == null)
        {
            throw new ArgumentNullException(nameof(state), "EngineTimer constructor requires a non-null argument.");
        }

        this.StateData = state;
    }

    /// <summary>
    /// Gets the object that was provided to the timer when it was instanced.
    /// This object will be provided to the callback at each interval when fired.
    /// </summary>
    public T StateData { get; private set; }

    /// <summary>
    /// Gets a value indicating whether the engine timer is currently running.
    /// </summary>
    public bool IsRunning { get; private set; }

    /// <summary>
    /// <para>
    /// Starts the timer, firing a synchronous callback at each interval specified until `numberOfFires` has been reached.
    /// If `numberOfFires` is 0, then the callback will be called indefinitely until the timer is manually stopped.
    /// </para>
    /// <para>
    /// The following example shows how to start a timer, providing it a callback.
    /// </para>
    /// @code
    /// var timer = new EngineTimer<IPlayer>(new DefaultPlayer());
    /// double startDelay = TimeSpan.FromSeconds(30).TotalMilliseconds;
    /// double interval = TimeSpan.FromMinutes(10).TotalMilliseconds;
    /// int numberOfFires = 0;
    /// 
    /// timer.Start(
    ///     startDelay, 
    ///     interval, 
    ///     numberOfFires, 
    ///     (player, timer) => player.Save());
    /// @endcode
    /// </summary>
    /// <param name="startDelay">
    /// <para>
    /// The `startDelay` is used to specify how much time must pass before the timer can invoke the callback for the first time.
    /// If 0 is provided, then the callback will be invoked immediately upon starting the timer.
    /// </para>
    /// <para>
    /// The `startDelay` is measured in milliseconds.
    /// </para>
    /// </param>
    /// <param name="interval">The interval in milliseconds.</param>
    /// <param name="numberOfFires">Specifies the number of times to invoke the timer callback when the interval is reached. Set to 0 for infinite.</param>
    public void Start(double startDelay, double interval, int numberOfFires, Action<T, EngineTimer<T>> callback)
    {
        this.IsRunning = true;

        this.timerTask = Task
            .Delay(TimeSpan.FromMilliseconds(startDelay), this.Token)
            .ContinueWith(
                (task, state) => RunTimer(task, (Tuple<Action<T, EngineTimer<T>>, T>)state, interval, numberOfFires),
                Tuple.Create(callback, this.StateData),
                CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
                TaskScheduler.Default);
    }

    /// <summary>
    /// Starts the specified start delay.
    /// </summary>
    /// <param name="startDelay">The start delay in milliseconds.</param>
    /// <param name="interval">The interval in milliseconds.</param>
    /// <param name="numberOfFires">Specifies the number of times to invoke the timer callback when the interval is reached. Set to 0 for infinite.</param>
    public void StartAsync(double startDelay, double interval, int numberOfFires, Func<T, EngineTimer<T>, Task> callback)
    {
        this.IsRunning = true;

        this.timerTask = Task
            .Delay(TimeSpan.FromMilliseconds(startDelay), this.Token)
            .ContinueWith(
                async (task, state) => await RunTimerAsync(task, (Tuple<Func<T, EngineTimer<T>, Task>, T>)state, interval, numberOfFires),
                Tuple.Create(callback, this.StateData),
                CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
                TaskScheduler.Default);
    }

    /// <summary>
    /// Stops the timer for this instance.
    /// Stopping the timer will not dispose of the EngineTimer, allowing you to restart the timer if you need to.
    /// </summary>
    public void Stop()
    {
        if (!this.IsCancellationRequested)
        {
            this.Cancel();
        } 
        this.IsRunning = false;
    }

    /// <summary>
    /// Stops the timer and releases the unmanaged resources used by the <see cref="T:System.Threading.CancellationTokenSource" /> class and optionally releases the managed resources.
    /// </summary>
    /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            this.IsRunning = false;
            this.Cancel();
        }

        base.Dispose(disposing);
    }

    private async Task RunTimer(Task task, Tuple<Action<T, EngineTimer<T>>, T> state, double interval, int numberOfFires)
    {
        while (!this.IsCancellationRequested)
        {
            // Only increment if we are supposed to.
            if (numberOfFires > 0)
            {
                this.fireCount++;
            }

            state.Item1(state.Item2, this);
            await PerformTimerCancellationCheck(interval, numberOfFires);
        }
    }

    private async Task RunTimerAsync(Task task, Tuple<Func<T, EngineTimer<T>, Task>, T> state, double interval, int numberOfFires)
    {
        while (!this.IsCancellationRequested)
        {
            // Only increment if we are supposed to.
            if (numberOfFires > 0)
            {
                this.fireCount++;
            }

            await state.Item1(state.Item2, this);
            await PerformTimerCancellationCheck(interval, numberOfFires);
        }
    }

    private async Task PerformTimerCancellationCheck(double interval, int numberOfFires)
    {
        // If we have reached our fire count, stop. If set to 0 then we fire until manually stopped.
        if (numberOfFires > 0 && this.fireCount >= numberOfFires)
        {
            this.Stop();
        }

        await Task.Delay(TimeSpan.FromMilliseconds(interval), this.Token).ConfigureAwait(false);
    }
}

I then created a series of unit tests for the class.

[TestClass]
public class EngineTimerTests
{
    [TestMethod]
    [TestCategory("MudDesigner")]
    [TestCategory("Engine")]
    [TestCategory("Engine Core")]
    [Owner("Johnathon Sullinger")]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Exception_thrown_with_null_ctor_argument()
    {
        // Act
        new EngineTimer<ComponentFixture>(null);
    }

    [TestMethod]
    [TestCategory("MudDesigner")]
    [TestCategory("Engine")]
    [TestCategory("Engine Core")]
    [Owner("Johnathon Sullinger")]
    public void Ctor_sets_state_property()
    {
        // Arrange
        var fixture = new ComponentFixture();

        // Act
        var engineTimer = new EngineTimer<ComponentFixture>(fixture);

        // Assert
        Assert.IsNotNull(engineTimer.StateData, "State was not assigned from the constructor.");
        Assert.AreEqual(fixture, engineTimer.StateData, "An incorrect State object was assigned to the timer.");
    }

    [TestMethod]
    [TestCategory("MudDesigner")]
    [TestCategory("Engine")]
    [TestCategory("Engine Core")]
    [Owner("Johnathon Sullinger")]
    public void Start_sets_is_running()
    {
        // Arrange
        var fixture = new ComponentFixture();
        var engineTimer = new EngineTimer<ComponentFixture>(fixture);

        // Act
        engineTimer.Start(0, 1, 0, (component, timer) => { });

        // Assert
        Assert.IsTrue(engineTimer.IsRunning, "Engine Timer was not started.");
    }

    [TestMethod]
    [TestCategory("MudDesigner")]
    [TestCategory("Engine")]
    [TestCategory("Engine Core")]
    [Owner("Johnathon Sullinger")]
    public void Callback_invoked_when_running()
    {
        // Arrange
        var fixture = new ComponentFixture();
        var engineTimer = new EngineTimer<ComponentFixture>(fixture);
        bool callbackInvoked = false;

        // Act
        engineTimer.Start(0, 1, 0, (component, timer) => { callbackInvoked = true; });
        Task.Delay(20);

        // Assert
        Assert.IsTrue(callbackInvoked, "Engine Timer did not invoke the callback as expected.");
    }
}

When I run the unit test coverage analysis in Visual Studio 2015, it tells me that the class is 100% covered by unit tests. However, I've only tested the constructor and the Start() method. None of the unit tests touch the Stop(), StartAsync() or Dispose() methods.

Why would Visual Studio tell me I am at 100% code coverage?

Code Coverage

Django: tests.py as a module

Background:

I'm using Django 1.8.

And I'm beginning to test on it.

When I use the models.py or views.py, I usually remove them, and create a module folder with the same name to replace.

In this way, I can split the models and views to different code files and make them easy to edit.


Question:

But when I tried to change the tests.py to a module folder, I found that the test cases in the __init__.py cannot run.

What's wrong? If I want to do so, is there any way?

Please help, thank you.

Karma Unit testing of Ionic App. Error: [ng:areq] Argument 'StockCtrl' is not a function, got undefined

I'm getting an error while trying to unit test my ionic app. I went through previously asked questions and non of the answers worked for me. Any ideas what I'm doing wrong?

Error I'm getting:

PhantomJS 1.9.8 (Mac OS X 0.0.0) StockCtrl should have a scope variable defined FAILED
TypeError: 'undefined' is not a function (evaluating 'queueableFn.fn.call(self.userContext)')
Error: [ng:areq] Argument 'StockCtrl' is not a function, got undefined
http://ift.tt/1JBjDXl
undefined
    at assertArg (/Users/Projects/online-shop/www/lib/angular/angular.js:1770)
    at assertArgFn (/Users/Projects/online-shop/www/lib/angular/angular.js:1781)
    at /Users/Projects/online-shop/www/lib/angular/angular.js:8975
    at /Users/Projects/online-shop/www/lib/angular-mocks/angular-mocks.js:1848
    at /Users/Projects/online-shop/test/stockController.spec.js:9
    at invoke (/Users/Projects/online-shop/www/lib/angular/angular.js:4450)
    at workFn (/Users/Projects/online-shop/www/lib/angular-mocks/angular-mocks.js:2404)
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.006 secs / 0.007 secs)

stockFactory.js

app.factory('stockService', function($resource){
 return $resource('js/http://ift.tt/1OTCTiR', 'items');
})

stockController.spec.js

app.controller("StockCtrl", function($scope, $rootScope, $stateParams, stockService) {

var items = stockService.get(function(){
    $scope.stock = items['items'];
  });
});

stockController.spec.js

describe('StockCtrl', function() {
  beforeEach(angular.module('Shop'));

   var scope;


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

  it("should have a scope variable defined", function() {
      expect(scope).toBeDefined();
   });
});

I have tried'module' instead of 'angular.module' as suggested in one of the previously posted questions but end up with other error:

Error: [$injector:modulerr] Failed to instantiate module Shop due to:
Error: [$injector:modulerr] Failed to instantiate module ionic due to:
Error: [$injector:nomod] Module 'ionic' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://ift.tt/1JBjEdz

I would be very grateful for a help.

Also, does anyone know how test $resource as a next step?

Espresso get dynamically created child in layout

Button.java

public class Button extends FrameLayout {
    public Button(Context context, AttributeSet attrs) {
        super(context, attrs);
        TextView textView = new TextView(context);
        textView.setText("Test");
    }
}

layout.xml

<LinearLayout>
    <com.Button id="button_1" />
    <com.Button id="button_2" />
</LinearLayout>

Using Espresso, how to access the TextView created in Button, and verify its text?

onView(withId(R.id.button_1)<get_child>).check(matches(withText("Test")));

symfony2 phpunit : how to drop and copy database before running tests?

In my symfony2 application, I am using phpunit to verify that the response from every route has a code 200.

Before I run the tests, I want to drop the test database and copy my production database under the name test (i.e. I want to reinitiate my test database).

I learned about the public static function setUpBeforeClass() but I am lost as to how drop and copy the database.

How can I do that ?

My class so far :

<?php

namespace AppBundle\Tests\Controller;

use AppBundle\FoodMeUpParameters;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

require_once __DIR__.'/../../../../app/AppKernel.php';


class ApplicationAvailabilityFunctionalTest extends WebTestCase
{

    public static function setUpBeforeClass()
    {

    }

    /**
     * @dataProvider routeProvider
     * @param $route
     */
    public function testAllRoutesAreLoaded($route)
    {
        $listedRoutes = $this->getListedRoutes();

        $this->assertArrayHasKey($route, $listedRoutes);
    }
}

How to specify test directory in Maven pom.xml

Maven handles java unit tests well by defaulting to:

src/test/java

We're writing quite a few Groovy unit tests right now, and I'd like to find a way in Maven to specify a folder such as:

src/test/groovy

as a test folder. This would help us to import a Maven project into, say, IntelliJ, without additional setup.

Someone mentioned this was possible, but I wasn't able to find a way searching the Maven docs, or SO. Does anyone know how to mark the directory in the pom?

Thank you

In Rust, what is the idiomatic way to have a private function tested?

The Rust book says that using a "tests" module is the idiomatic way to have unit tests. But I cannot see a function from the super module in the tests module if that function is not marked 'pub'. How should one test internal functions then?

My first instinct was to look for a way to #ifdef the keyword pub. I have done this in the past for C++ testing. For Rust what I have done is simply have tests for private functions in the module and then tests for the public interface in the "tests" module.

Am I doing it right?

Unit testing Collection in Java

I have a unit test that will allow me to iterate through a Collection object containing a list of vehicle. Upon each iteration, I want to check to see if the vehicle is an instance of automobile. So my code looks a bit like this:

public class VehicleChecker {
    protected boolean checkVehicles(Garage garage) {
        for (Vehicle vehicle : garage.getVehicles() {
            if (vehicle instanceof Automobile) return true;
        }
    }
}

So I wrote my code accordingly:

@Mock private Garage mockGarage;
@Mock private VehicleCollection mockVehicleCollection;
@Mock private VehicleCollectionIterator mockVehicleCollectionIterator;
@Mock private Vehicle mockVehicle;

@Test
public void testCheckVehicles() {

    VehicleChecker testObject = new vehicleChecker();

    when(mockGarage.getVehicles()).thenReturn(mockVehicleCollection);
    when(mockVehicleCollection.iterator()).thenReturn(mockVehicleCollectionIterator);
    when(mockVehicleCollectionIterator.hasNext()).thenReturn(true).thenReturn(false);
    when(mockVehicleCollectionIterator.next()).thenReturn(mockVehicle);

    boolean result = testObject.checkVehicles(mockGarage);

    verify(mockGarage).getVehicles();
    assertEquals(true, result);
}

The problem occurs with the verify statement. Based on how it was written, the test should pass. When I step through the code, however, I the code just skips the for loop entirely. Why is that? Is there a difference in the way one iterates through a Collection as opposed to an ArrayList? If so, how do I properly mock that interaction?

Should I use sut naming convention for unit tests

Some(including me) use the sut(system under test) to name the software being tested in unit tests.

Is this considered a good practice? why/why not?

Example:

[Test]
public void SetClaimUpdatedShouldCallSameMethodOnDependedServices()
{
    //Arrange
    var changedClaimService1 = new Mock<IChangedClaimsService>();
    var changedClaimService2 = new Mock<IChangedClaimsService>();

    var changedClaim = CreateAnyChangedClaim();

    var sut = new ChangedClaimsServiceComposite(
        changedClaimService1.Object,
        changedClaimService2.Object);

    //Act
    sut.SetClaimUpdated(changedClaim);

    //Assert
    changedClaimService1.Verify(x => x.SetClaimUpdated(changedClaim), "changedClaimService1");
    changedClaimService2.Verify(x => x.SetClaimUpdated(changedClaim), "changedClaimService2");
}

using a mocked controller context to test a controller

I am trying to run unit tests against a controller decorated with the [Authorize] attribute. The solutions I have found on SO indicate that I should use Moq to mock the authorization. The solution code can be found here.

var controller = new UserController();
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;

I have implemented the above solution in my test:

var controller = new HomeController();
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;

var result = controller.GetStarted();
result.ExecuteResult(mock.Object);
Assert.IsTrue(false); //I am running with a breakpoint here

Result generates, but when I try to execute the result with the mocked controllerContext, I get an error. How do I use the mocked ControllerContext to test the controller?

The skeleton code for the controller is:

[Authorize]
public ActionResult GetStarted()
{
    if (User.Identity.IsAuthenticated)
    {
        var user = CommonUtil.Instance.UserManager.FindByName(User.Identity.Name);
        if (user != null)
        {
            ViewBag.IsAdministrator = user.Roles.Contains("Administrators");
            ViewBag.IsActiveUser = user.Roles.Contains("ActiveUsers");
        }
    }
    return View();
}

I have a feeling this is a trivial fix, but I have no idea what I am doing, so it seems impossible.

Karma PhamtonJS TypeError: 'undefined' is not a function (evaluating 'React.renderComponent

I'm trying to set up React component testing using Webpack, Karma and PhantomJS.

I cannot seem to find why I get the following error when I run npm test:

PhantomJS 1.9.8 (Windows 8 0.0.0) Module Header should display text FAILED TypeError: 'undefined' is not a function (evaluating 'React.renderComponent(instance, div)')

I have the following test file

'use strict';




describe('Module', function(){

  var component;

  beforeEach( function(){
    var React = require('react-addons');
    var TestUtils = React.TestUtils;
    var Header = require('../Header');
    var component = TestUtils.renderIntoDocument(<Header title="Test Title" />);
  });


  it('Header should display text', function(){

    expect(component.getDOMNode().textContent).toMatch(/Test Title/);
  });


});

It seems that TestUtils.renderIntoDocument(); is the problem , does anyone know how I can fix this ?

Thanks for your time.

Unit Test AuthorizeAttribute throws Object ref not set when attr [duplicate]

This question already has an answer here:

Hi I am trying to test my Custom AuthorizeAttribute.

It all works fine when the attribute returns false, but when the attribute returns true I get an : Object reference not set to an instance of an object.

Why on success would it throw this exception? I am assuming i am missing a setup but not sure what it is?

 [TestMethod]
        public void Given_AttributeReturnsTrue_Should_HttpUnauthorizedResult()
        {
            var context = new Mock<HttpContextBase>();

            context.Setup(c => c.Items).Returns(new Dictionary<object, object>());
            context.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);
            context.SetupGet(x => x.Request).Returns(_requestMock.Object);

            var descriptorMock = new Mock<ActionDescriptor>();
            descriptorMock.Setup(a => a.ActionName).Returns("Index");
            var controllerDescriptor = new Mock<ControllerDescriptor>();

            descriptorMock.Setup(a => a.ControllerDescriptor).Returns(controllerDescriptor.Object);
            var controllerBase = new Mock<ControllerBase>();

            var controllerContext = new ControllerContext(_contextMock.Object, new RouteData(), controllerBase.Object);
            var authorisationContext = new AuthorizationContext(controllerContext, descriptorMock.Object)
            {
                HttpContext = controllerContext.HttpContext
            };

            SetupBusinessLogic(false);// this just setsup the logic to return false in the Attribute class when i step through attribute returns false

            attributeToTest.OnAuthorization(authorisationContext);

            authorisationContext.Result.ShouldBeOfType<HttpUnauthorizedResult>(); // test passes
        }

        public void Given_AttributeReturnsFalse_Should_DoSomething()
        {
            var context = new Mock<HttpContextBase>();

            context.Setup(c => c.Items).Returns(new Dictionary<object, object>());
            context.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);
            context.SetupGet(x => x.Request).Returns(_requestMock.Object);

            var descriptorMock = new Mock<ActionDescriptor>();
            descriptorMock.Setup(a => a.ActionName).Returns("Index");
            var controllerDescriptor = new Mock<ControllerDescriptor>();

            descriptorMock.Setup(a => a.ControllerDescriptor).Returns(controllerDescriptor.Object);
            var controllerBase = new Mock<ControllerBase>();

            var controllerContext = new ControllerContext(_contextMock.Object, new RouteData(), controllerBase.Object);
            var authorisationContext = new AuthorizationContext(controllerContext, descriptorMock.Object)
            {
                HttpContext = controllerContext.HttpContext
            };

            SetupBusinessLogic(true);// this just setsup the logic to return true in the Attribute class when i step through attribute returns true

            attributeToTest.OnAuthorization(authorisationContext); // THROWS ERROR HERE OBJECT REF NOT SET TO REFERENCE OF OBJECT


        }

Unit testing angular with ui-router shows error related to $state

I have a very simple controller:

angular.module("myApp").controller("TestCtr", function ($scope) {
        $scope.value = 5;
        $scope.func = function () {
            return 10;
        };
    });

And I am about to start learning how to do unit tests using karma.. The problem is that myApp has module dependencies

angular.module("myApp",["ui.router", "blueimp.fileupload", "ui.bootstrap"]);

I started writing some test code ...

describe("TestCtrl", function($log) {
    "use strict";

    it("first test", function () {
        expect(1).toEqual(1);
    });

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

    beforeEach(inject(function() {}));
});

Everything works fine but when I add the last line, trying to start injecting things I get this error..

e 44.0.2403 (Windows 7 0.0.0) CreateCtrl first test FAILED
        Error: [$injector:unpr] Unknown provider: htmlTemplateCacheBusterProvider <- htmlTemplateCacheBuster <- $http <- $templateFactory <- $view <- $state
        http://ift.tt/1KFD9k1
            at C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:63:12
            at C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:3994:19
            at Object.getService [as get] (C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:4141:39)
            at C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:3999:45
            at Object.getService [as get] (C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:4141:39)
            at C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:8777:23
            at forEach (C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:323:20)
            at $HttpProvider.$get (C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:8775:5)
            at Object.invoke (C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:4182:17)
            at C:/Workspace/myApp/Dev/UI/app/lib/angular/1.3.9/angular.js:4000:37
Chrome 44.0.2403 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.028 secs / 0.015 secs)

I assume it has to do with ui-router that needs to be injected in the module.

If anyone could help me I would appreciate it! I am using Angular and Mocks v 1.3.9 and ui-router 0.2.13...

Thanks

Testing formsets in Django

How do I pass the values of a formset in a unit test using client self.client.post('/url/', {})? I am getting a validation error saying management_form tampered.

Thanks in advance!

JMockit mocking System.currentTimeMillis()

Running this test:

@Test
public void testSystemCurrentTimeMillis() {
    new NonStrictExpectations(System.class) {{
        System.currentTimeMillis(); result = 1438357206679L;
    }};
    long currentTime = System.currentTimeMillis();
    assertEquals(1438357206679L, currentTime);
}

I get an IllegalStateException:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
    at unittests.DateTest$1.(DateTest.java:24)
    at unittests.DateTest.testSystemCurrentTimeMillis(DateTest.java:23)

What's wrong with my Test (JMockit 1.18)?

angular unit test stateful filter

I have a filter that depends upon a service to retrieve some configuration, and hence I have made the filter stateful. It works great! However, I'd like to add unit tests around it but can't work out how to implement them.

An example filter:

.filter("myFilter", function(myService) {
    var data = null, serviceInvoked = false;

    function realFilter(value) {
        return data + value;
    }

    filterStub.$stateful = true;
    function filterStub(value) {
        if( data === null ) {
            if( !serviceInvoked ) {
                serviceInvoked = true;
                myService.get().then(function(result){
                    data = result;
                });
            }
            return "-";
        }
        else {
            return realFilter(value);
        }
    }

    return filterStub;
});

I can test that a blank string is initially returned.

In my next test I have stubbed myService with sinonjs and return a promise. I want to resolve that promise with data and see that the filter updates correctly.

Android Studio Mark Directory as Test Sources Root

I've done something in build.gradle to remove the green highlighting of the androidTest.java package.

I don't know how to get it back.

IntelliJ has a "Mark directory as test sources root" option in the context menu but I can't find the equivalent in Android Studio.

Is there a way to define this folder so I can start testing? (If it means anything, the test java files all have an icon of a "J" with a red circle around it)

karma jasmine not executing all tests

so i have 6 karma jasmine tests, in one file i have 3, which im testing all my factories

the test file for the factory is as followed

describe('Quiz Factories', function() {

    beforeEach(function() {

        //Ensure angular modules available
        beforeEach(module('geafApp'));

        beforeEach(inject(function (_counter_) {
            counter = _counter_;
        }));

        beforeEach(inject(function (_answer_sheet_) {
            answer_sheet = _answer_sheet_;
        }));

        beforeEach(inject(function (_questions_) {
            questions = _questions_;
        }));

    });

    it('it should return a number', function () {
        expect(counter).toBeNumber();
    });

    it('it should return an empty object', function () {
        expect(answer_sheet).toBeEmptyObject();
    });

    it('it should return an empty object', function () {
        expect(questions).toHaveObject(answers);
    });

});

in my console log its showing executed 4 of 6

PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 4 of 6 SUCCESS (0.004 secs / 0.029 secs)

So for some reason after the first it 'it' in the factory test file its skipping over the other two, even though there is no failures and all are contained in a beforeEach

Don't understand how interactions really work in Spock

Here's a super easy spock test case in Groovy.!! All classes/interface defined in this specification file. (A specification file in spock is simply a test case file).

Cannot seem to understand the workflow. How're mock objects being instantiated, injected, and destroyed in the test case workflow? Any help is appreciated...

Spock should be called 'Spooky', in my honest opinion ( :-) ), at least until one's very familiar with it..

import spock.lang.Specification

class WeatherServiceImpl {
    private URLAdapter urlAdapter;
    private URLConnection urlConn;

    public WeatherServiceImpl(urlAdapter){
        this.urlAdapter=urlAdapter
    }

    def run(city) {
        urlConn=urlAdapter.openConnection(city)
        return urlConn.getResponseCode()

    }

}

interface URLAdapter {
    def openConnection(city)

}


class WeatherServiceImplSpec extends Specification {

    def mockURLAdapter = Mock(URLAdapter)
    def mockURLConn    = Mock(HttpURLConnection)
    def weatherService=new WeatherServiceImpl(mockURLAdapter);


    def "Need to figure out the effects of lines: 'troublesome' and 'weirdo' "() {
        given:
        mockURLConn.getResponseCode()>> 9999
        mockURLAdapter.openConnection(_)>>mockURLConn;

        when:
        def result=weatherService.run("New York")

        then:
        // Uncommenting line 'troublesome' below throws a null-pointer exception:
        // java.lang.NullPointerException: Cannot invoke method getResponseCode() on null object
        //      at WeatherServiceImpl.run(URLAdapterConnectionSpec.groovy:29)
        //      at WeatherServiceImplSpec.delivers events to all subscribers(URLAdapterConnectionSpec.groovy:54)

        // Commenting out line 'troublesome' gives no issue!!

        // Line 'troublesome':
        // 1*mockURLAdapter.openConnection(_)

        // Line 'weirdo':
        // And yet, line 'weirdo' works just fine (i.e. test passes, no exception thrown)!!
        1*mockURLAdapter.openConnection(_)>>mockURLConn;

        //WTH is happening! ?
        result==9999


    }

}

Mocha async test handle errors

I'm trying to create a test case with Mocha but my code is asynchronous.

That's fine, I can add a "done" callback function to "it" and that will work perfectly fine for positive cases. But when trying to test negative cases, it will just make the test fail.

I would like to make something like this but asynchronous:

someObject.someMethod(null).should.equal(false)

Instead I can only test for a callback to return, instead of testing what really happend (null is not valid):

it('this should return false or an error', function(done) {
    someObject.someMethod(null, '', done);
});

I would like to write something like this:

it('this should return false or an error', function(done) {
    someObject.someMethod(null, '', done).should.throw();
});

but that would lead to this error:

"TypeError: Cannot read property 'should' of undefined"

I also tried using expect and assert, but the same rules apply.

Any clues? Thanks

How do I import across submodules

We've got a test framework using nose and factory_boy up and going.

As recommended, we've put a /test directory inside of each module directory and that's where we put a factories.py file and the various test cases.

The challenge I've got is trying to import factories and functions between these test submodules. Full code branch is here:

http://ift.tt/1VRh0Fr

In case I haven't relayed enough detail to be useful.

Detailed problem

The summary of the relevant structure is:

/gbe
    __init__.py
    tests.py
    (many more files)
    /tests
         __init__.py
         factories.py
         functions.py
         (many files of tests, all tests_*)
/ticketing
    __init__.py
    tests.py
    /tests
         __init__.py
         factories.py
         test_edit_event.py

It's in that last folder that problem is happening.

I can't seem to import anything from gbe.tests and I want to reuse the mocks provided in factories.py and the functions in functions.py

Whatever I try, consistently results in the form of either:

Traceback (most recent call last):
File "/Users/bethlakshmi/Documents/mysite/GBE2/expo/ticketing/test/test_edit_event.py", line 27, in setUp
self.privileged_user = gbe_tests.factories.ProfileFactory.create().user_object
AttributeError: 'module' object has no attribute 'factories'

or something similar to:

Traceback (most recent call last):
    File "/Library/Python/2.7/site-packages/nose/loader.py", line 420, in loadTestsFromName
      addr.filename, addr.module)
    File "/Library/Python/2.7/site-packages/nose/importer.py", line 47, in importFromPath
      return self.importFromDir(dir_path, fqname)
    File "/Library/Python/2.7/site-packages/nose/importer.py", line 94, in importFromDir
      mod = load_module(part_fqname, fh, filename, desc)
    File "/Users/bethlakshmi/Documents/mysite/GBE2/expo/ticketing/test/test_edit_event.py", line 12, in <module>
      import gbe.tests.factories as gbe_fact

    ImportError: No module named factories

Things I've tried:

  • various variations on "from gbe.tests import functions, factories"
  • various forms of "import gbe.tests as gbe_test" and rename the calls to the factories and functions accordingly.
  • messing with the init.py file to import there, or to set the all to functions.py and factories.py

The command I'm trying to run is:

./manage.py test ticketing

As far as I can tell, to the code, the internal contents of gbe.tests just doesn't exist. I have no problem importing gbe.models, gbe.views, gbe.functions, etc. Nor do I have a problem with anything in /ticketing

I've read every question in stackoverflow that I can find with no success.

90% of the accepted answers seem to be "make sure you have an init.py" - which is already true in my case.

I also tried messing with the system path, with no success.

Note:

You'll see that I repeated the factories I want to mock in the ticketing/tests/factories.py - that's the only way I can get the tests in ticketing to run, and I refuse to have broken tests in a check-in if I can help it.

I've tried removing those classes, and the errors above prevail - when I CAN refactor to remove this redundant code, I will do so with great joy.

Final Question

What am I missing?

Mocked Service in a Directive

The idea is to mock the service based on the gist. Where the service is redefined and then the injection happens, the new overwritten service is used by the directive/controller.

How it's possible to inject the overwritten on the directive? The following snippet shows how it's inserted on the controller:

beforeEach(inject(function($controller, $rootScope, _UserService_) { // inject mocked service
    scope = $rootScope.$new();

    ctrl = $controller('MyController', {
        $scope: scope,
        UserService: _UserService_
    });

}));

zk app unit Testing

I have an app developed with zk. Its composed as 3 modules : GUI project(UI zul page, comptroller, ejb lookup DAO for each Ji) common project(common utility classes exist), ejb project (where we place all our transaction pieces). We need to start with unit testing. My question , how to start with. Knew with jUnit,selenium and some zk supported testing tool. 1. My UI operation connects to ejb module for DB operations which basically all screens as well user operation ends with. How to start with these scenarios. Controller part listens for event handling, sets some page/session attribute, does some validation and throws 'WrongValueException' on the Ji components.....

How can I unit test an MVC Action that returns a PartialViewResult with null model?

I am new to unit testing.

I have an action:

[HttpPost]
public PartialViewResult Details(Details model, string action)
{
    // .. some logic
    return this.PartialView("_details", model);
}

and I want to write a test for a situation when the model passed to the action is null and/ or action parameter is empty.

How to do such a test?

Create a new phase in maven?

I'm trying to do this: mvn rest. Is should test all the test cases I've written in a package under main/src/test/java/rest and should not test other cases outside this package or in any other package.

When I do mvn test, it tests all the cases which I do not want.

So my question is it possible? If yes, how?

I've read that it can be done by creating a new plug-in in pom.xml. I read this article on Configuring Plug-ins. I've tried the following but it didn't work out for me.

<plugin>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>spring-mock-mvc</artifactId>
    <version>2.2.0</version>
    <executions>
      <execution>
        <id>rest</id>
        <phase>test</phase>
        <goals>
            <goal>main/src/test/java/rest</goal>
        </goals>
      </execution>
    </executions>
</plugin>

I'm getting the following error when I do: mvn rest

[ERROR] Unknown lifecycle phase "rest". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycl e phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-t est-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site , post-site, site-deploy.

What am I doing wrong? Thank you.

How to create unit-testing for array function in AngularJS with Jasmine

I have xf array: var xf = []; And I have a function is a element in this array and a function to use it:

$scope.checkEmailValid = function () {
                var result = false;
                Iif (xf.validateEmail($scope.email, '256')) {
                    result = true;
                }
                return result;
            };

xf.validateUsername = function (sText) {
            var isValid = false;

            do {
                //    Check for valid string.
                isValid = typeof sText === 'string';
                if (!isValid) {
                    break;
                }

                //  Check that each special character does not exist in string.
                for (var i = 0; i < sText.length; i++) {
                    if (xf.SPECIAL_CHARS.indexOf(sText.charAt(i)) !== -1) {
                        isValid = false;
                        break;
                    }
                }

                if (!isValid) {
                    break;
                }

            } while (false);

            return isValid;
        };

But when i run my spec:

it ('checkEmail', function(){
     $controller('MyCtrl', { $scope: $scope });
     xf.validateUsername();
     spyOn(window,xf.validateUsername).and.callThrough();
});

It make error:

xf.validateUsername is not a function

How can I cover it?

Inject Context in ActivityInstrumentationTestCase2

I am writing espresso tests for my Android application. I have an ActivityInstrumentationTestCase2, where I want to inject a context to use a test database instead of the actual database.

The test context I create in the setUp() method like this:

@Before
public void setUp() throws Exception {
    super.setUp();
    RenamingDelegatingContext context = 
            new RenamingDelegatingContext(getContext(), "test_");
    mActivity = getActivity();
    // Now how do I inject the new context to the activity?
}

How can I inject this context into my activity? And if I was able to inject it, will it be the new application context, or which context exactly?

I know that in ActivityUnitTestCase there is a method setActivityContext(Context), but in ActivityInstrumentationTestCase2 it is not there. Is there another way to set the context?

Owin hosted webapi 2.2. testing controller with mocked service.

I have webapi which for testing purposes I am hosting in owin. I have set it up using autofac. now when I am testing I want to inject moq dependencies. which I am not able to so far. I have read the documentation and did bit of research but I am missing something.

here is the testing code.

 [Test]
    public void Request_all_airports()
    {
        const int port = 8086;
        AirportCollection moqAirportCollection = new AirportCollection();
        moqAirportCollection.Airports = new List<Airport>{new Airport{IATA = "moq",Name = "moqName"}};

        using (WebApp.Start<Startup>("http://localhost:" + port))
        {
            using (var mock = AutoMock.GetLoose())
            {
                var moqObj =  mock.Mock<IAirportService>().Setup(x => x.GetAirports()).Returns(moqAirportCollection);

                var client = new HttpClient {BaseAddress = new Uri("http://localhost:" + port)};
                var response = client.GetAsync("/api/airport/get").Result;
                var body = response.Content.ReadAsStringAsync().Result;
                var airportCollection = JsonConvert.DeserializeObject<AirportCollection>(body);
            }
        }
    }

Please have a look. let me know what I am missing. if you want to look at controller code or any other piece do let me know .

Thanks

TestNg - How to merge two dataproviders horizontally

Can you please let me know if we can merge the below 2 dataproviders

public Object[][] dp1() {
   User user = new User(1L, "Arun");
   Transaction trx = new Transaction(1L, "atm");   
  return new Object[][] {
      new Object[] { user , trx, true  }

  };
}

public Object[][] dp2() {
  return new Object[][] {
      new Object[] { "e", "f" }
  };
}

I want to merge them horizontally, after merge the following output is desired in the merged dataprovider { user , trx, true, "e", "f" }

In unittest, how do I assert whether the function called or not NOT using mock

I want to test the class Procedures whether some function called or not. Since I know mock and often use it, firstly I used mock. However soon it later, I noticed this test was failed because using mock is just imitating the real processing.

What I want to do is the following test is passed correctly.

Does anyone have solutions?

from unittest import TestCase, mock


class Procedures:
    x = 1

    def func_should_be_called(self):
        self.x = 'called'
        return len(self.x)

    def hoge(self):
        self.func_should_be_called()
        # Because whenever self.x != 'called', Never do some_exec(), and I want to raise Exception
        assert self.x == 'called'
        self.some_exec()

    def some_exec(self):
        pass


class HogeTest(TestCase):
    def test_hoge(self):
        with mock.patch('test_hoge.Procedures.func_should_be_called') as mock_func_should_be_called:
            p = Procedures()
            mock_func_should_be_called.return_value = 5
            p.hoge()
            mock_func_should_be_called.called()

if __name__ == '__main__':
    Procedures().hoge()
    print('yes!')

In fact, I found inspect and traceback module and used it. However the code using them in the test-function(test_hoge) didn't work because old call-stack(func_should_be_called's) had been gone.

The purpose of the codes which under if __name__ == '__main__' is only verifying Procedures works correctly.

Mocking a return value in a sub object

I want to write a test case for a feature within complex data structures. The feature doesn't rely on all the data and getting real instances with the desired properties is hard. Hence, I am using Mocks.

def test_Case:
    t1 = Timeseries(...) # Data
    t2 = Timeseries(...) # Data

    fancy_t1 = Mock(data=d1, additional_property= ...)
    fancy_t2 = Mock(data=d2, additional_property= ...)

    container = Mock(data_sets=[fancy_t1, fancy_t2])

    ret = function_to_test(container)
    assert ret ... # Some condition

Within function_to_test there is a call of the form

container.aggregation.aggregate(fancy_t, more_arguments1, more_arguments2, ... )

What I want the aggregation.aggregate call to do is quite simple. It is supposed to evaluate to t1+t2 (a Timeseries) and ignore the fancy_t and the other arguments.

How would I do that?

If I do something like this

agg = Mock()
agg.return_value = d1 + d2
container.aggregation.get_aggregated_positions = agg

It evalutes to something like <Mock name='mock.aggregation.get_aggregated_positions()' id='296569680'> instead of a Timeseries.

How to Unit Test Methods with Sharepoint Objects as parameters with Microsoft Fakes

Im trying to write a unit test for methods that take sp objects as parameters like SPWeb or SPEventReceiverCollection etc. with Microsoft Fakes but have no idea how to mock these. I've used moq before but cant seem to find how to Mock in microsoft fakes. eg:

public List<SPEventReceiverDefinition> CheckExisting(SPEventReceiverDefinitionCollection recs)

Java rest server : make a unit test

I try to make a unit test for a standalone rest server. If I run the rest server it work nice. But I don't know how to make the UnitTest running.

My main class :

public class Main {

private static final int DEFAULT_PORT = 8080;
private final int serverPort;
private final Server restServer;
public Main(final int serverPort) throws Exception {
    this.serverPort = serverPort;

    restServer = configureServer();
    restServer.start();
    restServer.join();
}

public void close() throws Exception {
    if (restServer != null) {
        restServer.stop();
    }
}

private Server configureServer() {
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(Main.class.getPackage().getName());
    resourceConfig.register(JacksonFeature.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder sh = new ServletHolder(servletContainer);
    Server server = new Server(serverPort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(sh, "/*");
    server.setHandler(context);
    return server;
}

public static void main(String[] args) throws Exception {
    int serverPort = DEFAULT_PORT;
    if (args.length >= 1) {
        try {
            serverPort = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    new Main(serverPort);
}

The resource class :

@Path("builder")
public class ReportBuilderResource {

    @POST
    @Path("/build")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.TEXT_PLAIN})
    public String makeReport(final ReportDescription reportDescription) {
        return reportDescription.getName();
    }
}

My Unit test class :

public class ReportBuilderResourceTest extends JerseyTest {

@Override
public AppDescriptor configure() {
    return new WebAppDescriptor.Builder()
            .initParam(WebComponent.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName())
            .initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, ReportBuilderResource.class.getName())
            .build();
}

@Test
public void testBuildReport() throws Exception {
    System.out.println("Test Build Report");
    ReportDescription reportDescription = new ReportDescription();

    JSONObject jsonObject = new JSONObject(reportDescription);
    resource().path("builder/").post(jsonObject.toString());
}

And the output log :

juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating low level InMemory test container configured at the base URI http://localhost:9998/
Running com.fdilogbox.report.serveur.ReportBuilderResourceTest
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer start
INFO: Starting low level InMemory test container
juil. 31, 2015 9:48:53 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
Test Build Report
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter filter
INFO: 1 * Server in-bound request
1 > POST http://localhost:9998/builder/
1 > Content-Type: text/plain
1 > 
{"name":null,"report":null}

juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 405
1 < Allow: OPTIONS
1 < 

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.497 sec <<< FAILURE! - in com.fdilogbox.report.serveur.ReportBuilderResourceTest
testBuildReport(com.fdilogbox.report.serveur.ReportBuilderResourceTest)  Time elapsed: 0.496 sec  <<< ERROR!
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 405
    at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:709)
    at com.sun.jersey.api.client.WebResource.post(WebResource.java:238)
    at com.fdilogbox.report.serveur.ReportBuilderResourceTest.testBuildReport(ReportBuilderResourceTest.java:47)

I think the server is not "running" for the test. How can'I do this?

How to setup more complicated (IoC like) registration in AutoFixture

Is it possible to reuse production IoC container registration in integration tests when using AutoFixture?

The problem is that I need the following fixture setup to inject mocks if dependency is not registered and inject "real" database related dependencies

var fixture = new Fixture().WithMocks().WithRealDatabase()

The solution I've tried

internal static Fixture WithMocks(this Fixture fixture)
{
    fixture.Customize(new AutoMoqCustomization());
}

internal static Fixture WithRealDatabase(this Fixture fixture)
{
    var containerBuilder = new Autofac.ContainerBuilder();
    ...
    containerBuilder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
    containerBuilder.RegisterGeneric(typeof(Repository<>)).AsImplementedInterfaces()        
    containerBuilder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
        .Where(t => t.Name.EndsWith("Repository"))
        .AsImplementedInterfaces();
    ...
    fixture.Customizations.Add(new ContainerSpecimenBuilder(containerBuilder.Build()));
}

internal class ContainerSpecimenBuilder : ISpecimenBuilder
{
    private readonly IContainer container;

    public ContainerSpecimenBuilder(IContainer container)
    {
        this.container = container;
    }

    public object Create(object request, ISpecimenContext context)
    {
        var seededRequest = request as SeededRequest;

        if (seededRequest == null)
        {
            return new NoSpecimen(request);
        }

        var result = this.container.ResolveOptional(seededRequest.Request as Type);
        return result ?? new NoSpecimen(request);
    }
}

But the problem with this approach is that container.Resolve will not take into account already registered dependencies in AutoFixture.

Is there any alternative to solve this problem to have more complicated registrations?

jeudi 30 juillet 2015

Is it possible to use [TestMethod] attribute outside of the test project?

I feel that test methods should be placed right under the methods they are supposed to test. But in tutorials I found so far they only placed in [TestClass]es inside Unit Test Projects. Why is that necessary?

JS Unit Test not appearing in VS 2015 Test Explorer

I am new to JavaScript unit testing. I am trying to test typescript classes and my tests are also written in typescript, which somewhat looks like below:

/// <reference path="../../typings/qunit/qunit.d.ts" />
import Utility1 = require("../utility");//This is script I want to test.    

test("utility_test",function() {

    ...

    var result = ...;
    var expected = ...;
    equal(result, expected, "Test failed");
})

I am using VS 2015 with chutzpah test adapter installed as shown here. To be clear I have installed this to extension to vs 2015: Chutzpah Test Runner Context Menu Extension, and Chutzpah Test Adapter for the Test Explorer and also added Chutzpah NuGet package.

Yet when I build my project, the test doesn't appear in the Test Explorer. And when I tried to run the test from context menu, it fails with this error: Error: Error: Called start() outside of a test context while already started.

Can anyone please let me know where I am going wrong?

How to unit test code that runs celery tasks?

The app I am working on is heavily asynchronous. The web application runs a lot of tasks through celery depending on user actions. The celery tasks themselves are capable of launching further tasks.

Code such as the one shown below occurs in our code base quite frequently.

def do_sth():
    logic();
    if condition:
         function1.apply_async(*args)
    else:
         function2.apply_asynch(*args)

Now we want to start unit testing any new code that we write and we are not sure how to do this. What we would like to assert in our pytest unit tests is that we want to see if function1 actually got called. We do not want to necessarily run function1 itself as we will have a unit test for the function1.

I do not want to be running celery as a process, neither do I want to run any AMQP broker during the unit test session.

Is this achievable?

Error when testing PUT/POST methods of $resource using $httpBackend

I am having an issue where I am trying to test a service that has been set up using $resource, and has various methods GET, PUT, POST.

I am using $httpBackend in my tests, and it works fine when testing the GET requests but fails on the PUT/POST - I think it may be due to it sending an OPTIONS request first.

Strangely if I change the factory to use $http.post() instead of using $resource, the test passes fine.

Does anyone know a way around this? Can I turn off the OPTIONS request? Or something...?

Thanks!

service

angular.module('myApp')
.factory('Reports', function ($resource, ApiConfig) {
        return $resource(ApiConfig.urlBase + "/protected/HttpResource/:id",{},{
        update: {method: 'PUT'},
        get: {method: 'GET',isArray: true},
        search: {method: 'GET',isArray: false},
        save: {method: 'POST'}
    });
});

The ApiConfig.urlBase resolves to http://localhost:8080/... in the tests

test file

describe("Reports", function() {

beforeEach(module("myApp"));

beforeEach(inject(function(_Reports_, _$httpBackend_, _ApiConfig_) {
    Reports = _Reports_;
    $httpBackend = _$httpBackend_;
    ApiConfig = _ApiConfig_;
}));

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

describe("save method", function() {

    var report = {name: "TestReport", type: "HttpResource"};

    beforeEach(function() {
        url = ApiConfig.urlBase + "/protected/HttpResource/";
        $httpBackend.when("POST", url).respond();
    });

    it("should make POST request when save method called", function() {
        $httpBackend.expectPOST(url);
        Reports.save(report);
        $httpBackend.flush();
    });
});
});

Code Coverage analysis includes internal Types

I have a project that I ran the Visual Studio 2015 code coverage analysis against. In the results, it includes internal classes in the results hierarchy that I can't test against. I don't want to use the InternalsVisibleToAttribute, but I also don't like that it's counted as part of the code coverage path.

Is there a way to have visual studio ignore internal classes, so that the code coverage results only includes public classes that I can actually touch with unit tests?

Code Coverage

The CachedTypeData is an internal sealed class with a series of generic methods. As you can above the type is included in my results, right next to two public classes, Autosave<T> and EngineTimer<T>.

Unit test fixtures in Python?

I'm writing a library in Python which makes calls to a REST API, receives results in JSON, and returns Python class instances after transforming the results.

Is there a generally accepted way of including test fixtures (ie JSON files to test against) inside of the Python package and test namespace to load and test against in your test cases?

How to "Negative"-test method with try catch branch? [duplicate]

This question already has an answer here:

I have my method

public void devide(int a, int b){
     try{
         int c  = a/b;
     }catch(Exception e){
         e.printStackTrace();
     }
}

This in my test method

@Test
public void testDevide_notSuccess_ExceptionOccur(){
   int a=5;
   int b=0;
   devide(a,b); //of course will go to "catch" 
}

So my question is : how can i assert(or something) that tell me that the test case is going to "catch" branch?

Unit test $httpBackend with query params

Using $httpBackend, how can I use expectGET with a url that has query params? The order doesn't matter, and the value doesn't matter.

$httpBackend
  .expectGET('/api/my_endpoint/example?X=false&Y=someethingelse&Z=anotherthing')
  .respond(200, {});

Using $resource this is how I declare it:

  get: {
      method: 'GET',
      url: '/api/my_endpoint/example',
      params: {
        X: '@X',
        Y: '@Y',
        Z: '@Z',
      }
    }

Does Python unittest support customization for the report?

I like the fact that the unit test class will print out the nice summary about what pass and fail; although I can't see on the official documentation, how do you customize that output.

I see the msg parameter for the assert, which means that I can print a descriptive message when the assert trigger (test fail), but what if you want to include a summary on success?

How to write effective PHPUnit test cases

I've recently start writing test cases for my Angularjs app in Jasmine, I now want to start writing them for my PHP classes too.

Up until now i've basically been:

  • asserting that if the wrong sort of data/datatype is parsed to the method that it throws and exception
  • checking roughly that the right thing happens in the method (e.g. items are removed from arrays)
  • and that the right data type is returned from the method.

Is there anything else that I should be checking? Is any of this overkill already? Are there any tips that anyone can give me to writing really robust and effective test cases?

How to test angular directive scope

I am running to an issue for the unit test

I have something like

describe('test controller', function () {
    var =$compile, scope, rootScope;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_$compile_, _$rootScope_) {
       $compile   = _$compile_;
        rootScope   = _$rootScope_;
        scope        = _$rootScope_.$new();
    }));

    describe('test', function() {
        beforeEach(function () {
            scope.toys = ['toy1', 'toy2'];            
        });
        it('should test directive' , function() {
            var element = $compile('<button type="button"  show-item>See all</button>')($rootScope);
            element.triggerHandler('click');
            $rootScope.$digest();
        });
    });
});

html

   <button type="button"  show-item>See all</button>

Directive

angular.module('myApp').directive('showItem', 
function() {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, elem, attrs) {                
            elem.bind('click', function() {
                var l = scope.toys.length;
                //other codes
            });
     }
});

I am getting undefined' is not an object (evaluating 'scope.toys.length') when I run the unit test.

I am not sure what went wrong as I already specify scope.toys inside beforeEach function. Can anyone help me about it? Thanks a lot!

How to test non-public methods?

I am learning Scala and wrote Email class which looks like

class Email(emailConfigName: String) {
  private val emailConfig = ConfigFactory.load(emailConfigName) getConfig ("email")

  def notifySupportForTenant(symbolicName: String) {
    val emailMessage: Message = constructEmailMessage(symbolicName)
    Transport.send(emailMessage)
  }

  def constructEmailMessage(symbolicName: String): Message = {
    val message = createMessage(emailConfig getString ("shn.mail.smtp.host"))
    message setFrom (new InternetAddress(emailConfig getString ("shn.mail.from")))
    // todo: should come from API (sent by client)
    message setSentDate (new Date())
    message setSubject (emailConfig getString ("shn.mail.subject") replace("TENANT_ID", symbolicName))
    message setContent(emailConfig getString ("shn.mail.body"), "text/html")
    message.setRecipients(Message.RecipientType.TO, getMessageRecipients(emailConfig getString ("shn.mail.recipient")))
    message
  }

  private def createMessage(smtpHost: String): Message = {
    val properties = new Properties()
    properties put("mail.smtp.host", smtpHost)
    val session = Session.getDefaultInstance(properties, null)
    return new MimeMessage(session)
  }

  private def getMessageRecipients(recipient: String): Array[Address] = {
    // had to do the asInstanceOf[...] call here to make scala happy
    val addressArray = buildInternetAddressArray(recipient).asInstanceOf[Array[Address]]
    if ((addressArray != null) && (addressArray.length > 0)) addressArray
    else
      throw new IllegalArgumentException("no recipients found to send email")
  }

  private def buildInternetAddressArray(address: String): Array[InternetAddress] = {
    // could test for a null or blank String but I'm letting parse just throw an exception
    return InternetAddress.parse(address)
  }
}

I want to test this class's public API, notifySupportForTenant but this is not good for Unit Test since it also calls Transport.send(emailMessage) which will send the email.

All I am interested in testing if the message is constructed correctly. Which means I need to test constructEmailMessage

In order to test this, I had to make this public which is also exposed as public interface, which I do not prefer

What can I do?

Testing Ember.js files with JUnit

Mainly asking if this is possible, since I have always thought that JS files would be tested with a JS unit test framework, just like Java files would be tested with Java unit test frameworks. From quite a bit of Google searches I've only found results for plugins and this example: http://ift.tt/1NFYQCG

  1. Is unit testing something like Ember files possible in a Java-based framework like JUnit?

  2. Is there a way to convert QUnit tests to JUnit tests?

How can I setup a unique argument for the function passed to pool.map?

I'm trying to run multiple instances of a selenium webdriver in a unittest. I came across this post concerning threading: Python multithreading for dummies

It seems like I'd be able to implement the map function since my main runTest method just iterates over some database rows while using the webdriver to visit a page and verify data from the database. How can I pass a unique webdriver instance to each worker though?

import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

urls = [
  'http://www.python.org', 
  'http://ift.tt/Uac8wQ',
  'http://ift.tt/1IbyHGu',
  'http://ift.tt/1maEdNN',
  'http://ift.tt/sY1R1N',
  'http://ift.tt/So7VCZ',
  'http://ift.tt/1IbyGCu',
  'http://ift.tt/1iu7Zh8',
  ]

# Make the Pool of workers
pool = ThreadPool(4) 

I'd like to be able just do something like this:

# Open the urls in their own threads and return the results
results = pool.map(urllib2.urlopen, UNIQUE_WEBDRIVER_INSTANCE, urls)

#close the pool and wait for the work to finish 
pool.close() 
pool.join() 

Unit tests and testing the test

My app has the ability to update an item. I would like to create a unit test for this.

This is in c# using Moq. When I call the setup method in mock. I am having it take an existing item, and then update it as needed.

      messageMock.Setup(m => m.SaveMessage(It.IsAny<Message>())).Callback((Message msg) =>
        {
            var oldMsg = _messages.FirstOrDefault(m => m.Id == msg.MessageID);
            if (oldMsg != null)
            {
                oldMsg.Description = msg.Description;
                oldMsg.IsActive = msg.IsActive;
                oldMsg.Name = msg.Name;
                oldMsg.Type = msg.Type;
            }
        }).Verifiable();

If the logic of updating the item is done in Moq, then I am just testing the test. How can I test the business logic of update functionality?

how to unit test accountcontroller -nunit test(help) this is mvc accountcontroller

How do I unit test this?-Nunit. ??? thanks - this is accountcontroller of MVC, I want to unit test please help with code

public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set 
        { 
            _signInManager = value; 
        }
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    //
    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

    //
    // GET: /Account/VerifyCode
    [AllowAnonymous]
    public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
    {
        // Require that the user has already logged in via username/password or external login
        if (!await SignInManager.HasBeenVerifiedAsync())
        {
            return View("Error");
        }
        return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
    }

    //
    // POST: /Account/VerifyCode
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // The following code protects for brute force attacks against the two factor codes. 
        // If a user enters incorrect codes for a specified amount of time then the user account 
        // will be locked out for a specified amount of time. 
        // You can configure the account lockout settings in IdentityConfig
        var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent:  model.RememberMe, rememberBrowser: model.RememberBrowser);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(model.ReturnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid code.");
                return View(model);
        }
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit http://ift.tt/1vUusLV
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    //
    // GET: /Account/ConfirmEmail
    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string userId, string code)
    {
        if (userId == null || code == null)
        {
            return View("Error");
        }
        var result = await UserManager.ConfirmEmailAsync(userId, code);
        return View(result.Succeeded ? "ConfirmEmail" : "Error");
    }

    //
    // GET: /Account/ForgotPassword
    [AllowAnonymous]
    public ActionResult ForgotPassword()
    {
        return View();
    }

Chaining methods with Moq

I'm attempting to mock and setup chained methods using Moq.

Here is the method I am trying to mock:

TeamMember teamMember = _unitOfWork
    .TeamMembers
    .Query()
    .ToList()
    .Where(t => t.AssociationCode.ToString() == code 
        && Crypto.EncryptStringAES(t.Id.ToString(), sharedSecret) == hash)
    .SingleOrDefault();

and here is where I attempt to mock it:

var unitOfWorkMock = new Mock<IUnitOfWork>();
var iQueryableMock = new Mock<IQueryable<TeamMember>>();
var iToListMock = new Mock<List<TeamMember>>();
var whereMock = new Mock<IList<TeamMember>>();
var singleMock = new Mock<IEnumerable<TeamMember>>();

unitOfWorkMock
    .Setup(u => u.TeamMembers
        .Query())
        .Returns(iQueryableMock.Object);

iQueryableMock
    .Setup(i => i.ToList())
        .Returns(iToListMock.Object); //This line throws the error

whereMock
    .Setup(w =>
            w.Where(It.IsAny<Func<TeamMember, bool>>()))
        .Returns(singleMock.Object);

singleMock
    .Setup(s =>
            s.SingleOrDefault())
        .Returns(new TeamMember()
        {
            Email = "Test@TeamMember.com"
        });

When I run this test it gives me this error:

Expression references a method that does not belong to the mocked object: i => i.ToList<TeamMember>()

I have looked at this question already and have tried to do something similar, but I must be missing something.

I am new to this, so if anyone can help me out it will be greatly appreciated.

Parameterized Unit Tests with Visual Studio 2015 Intellitest

One feature I've wanted to see in MSTest for a long time has been Parameterized Unit Tests (PUTs). I was excited to hear that Intellitest would be capable of creating said tests. I've started playing with Intellitest, however, and I'm thinking my definition of PUTs is different than Microsoft's.

When I think "PUT", I think TestCases in NUnit, or Theories in xUnit. People much smarter than me seem to use the same terminology.

Can someone tell me if Intellitest is actually capable of creating a PUT in the same way NUnit or xUnit might, or is this an issue of an overloaded term meaning one thing in Intellitest, and another to most other testing frameworks? Thanks.

Resharper 9 and Jasmine 2.x references

in the past I have used webstorm, karma, jasmine and phantom to run js tests. I have to now run tests within VS2015 and opted for resharper/jasmine and phantom js. I have my tests running ok and its actually looking good. The only gripe I have is that with karma you could specify wild card references and hence using a config all the referenced dependent js files are in one location. Now Im having to specify references in every spec file that I create. Is there an better way of doing this?

e.g. at the top of my spec file I have a couple of these:

///<reference path="~/Scripts/jasmine/jasmine.js"/>
///<reference path="~/Scripts/jasmine/jasmine.js"/>
///<reference path="~/Scripts/jasmine/jasmine-html.js"/>
///<reference path="~/Scripts/jasmine/boot.js"/>
///<reference path="~/Scripts/angular-core/angular.js"/>

and each file has much of the same references copied and pasted.

As a side note - I have also noticed that under the scripts folder in my mvc app there is an auto gen _references.js file that seems to have all my referenced files in it (though some paths are relative) - not sure that that is!

thanks

XCTest: Passing a function parameter

From XCTest file, I am calling a web service call and had put a wait block using "self.waitForExpectationsWithTimeout" API and to get the service response.

I have few test methods to be executed with this service response. When I store this response in a global variable and access it from other test function, this variable is coming as nil. What needs to be done here? Can I pass it as a function parameter?

Thanks

Unit test fails on PITclipse but succeeds in JUnit

In PITclipse, I am receiving this error after the test:

Exception in thread "main" org.pitest.help.PitHelpError: All tests did not pass without mutation when calculating line coverage. Mutation testing requires a green suite.
See http://pitest.org for more details.
    at org.pitest.coverage.execute.DefaultCoverageGenerator.verifyBuildSuitableForMutationTesting(DefaultCoverageGenerator.java:104)
    at org.pitest.coverage.execute.DefaultCoverageGenerator.calculateCoverage(DefaultCoverageGenerator.java:89)
    at org.pitest.coverage.execute.DefaultCoverageGenerator.calculateCoverage(DefaultCoverageGenerator.java:46)
    at org.pitest.mutationtest.tooling.MutationCoverage.runReport(MutationCoverage.java:118)
    at org.pitest.mutationtest.tooling.EntryPoint.execute(EntryPoint.java:101)
    at org.pitest.mutationtest.tooling.EntryPoint.execute(EntryPoint.java:43)
    at org.pitest.mutationtest.commandline.MutationCoverageReport.runReport(MutationCoverageReport.java:71)
    at org.pitest.mutationtest.commandline.MutationCoverageReport.main(MutationCoverageReport.java:43)
    at org.pitest.pitclipse.pitrunner.PitRunner.runPIT(PitRunner.java:49)
    at org.pitest.pitclipse.pitrunner.PitRunner.main(PitRunner.java:28)

It says the tests did not past, however JUnit has no errors or failures.

Not sure what the cause of this is so if you need any further information, please ask.

XCTest fails with with exception 'Non-UI clients cannont be autopaused'

I am trying to test creation of CLLocationManager as a singletone with default parameters:

+ (GeolocationService *)defaultGeolocationService
{
    static GeolocationService *_defaultGeolocationService = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _defaultGeolocationService = [[GeolocationService alloc] init];
        [_defaultGeolocationService initLocationManager];
    });

    return _defaultGeolocationService;
}

- (void)initLocationManager
{
    self.locationManager = [CLLocationManager new];
    self.locationManager.delegate = self;
    self.locationManager.pausesLocationUpdatesAutomatically = YES;
    [self.locationManager requestAlwaysAuthorization];
}

Test looks like this:

- (void)testInitWithDefaultsSettings
{
    GeolocationService *defaultGeolocationService = [GeolocationService defaultGeolocationService];

    XCTAssertTrue(defaultGeolocationService.settings.autoPause, @"autoPause");
}

And I get an exception: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Non-UI clients cannont be auto paused'

What should I do to make this test work?