lundi 29 février 2016

ChefSpec unable to find cookbook

When I run my unit test case (written in ChefSpec) I get the following error:

Chef::Exceptions::CookbookNotFound: Cookbook azuredns not found. If you're loading azuredns from another cook book, make sure you configure the dependency in your metadata

Following are my spec file, recipe file and metadata file

azuredns/spec/get_azure_token_spec.rb

require 'chefspec'
require 'rest-client'

describe 'azuredns::get_azure_token' do
  let(:chef_run) do
    # Step into the provider
    runner = ChefSpec::SoloRunner.new(step_into: ['azuredns_token'])
    # Read test data from a json file
    file_path = File.expand_path('test_data.json', __dir__)
    file = File.open(file_path)
    contents = file.read
    node_attr = JSON.parse(contents)
    # Load test data into node object
    runner.node.consume_attributes(node_attr)
    runner.converge(described_recipe)
  end

  before(:each) do
    # Mock post method of RestClient
    allow(RestClient).to receive(:post)
      .and_return({ access_token: 'i-am-a-token' }.to_json)
  end

  it 'retrieves token' do
    expect(chef_run).to retrieve_azuredns_token('azure_token')
  end

  it 'varifies the expected value of azure_rest_token' do
    expect(chef_run.node['azure_rest_token']).to eq('Bearer i-am-a-token')
  end

  it 'does not retrieve token due to incorrect resource name' do
    expect(chef_run).to_not retrieve_azuredns_token('azure_token1')
  end

  it 'raises exception due to error in response' do
    # Mock post method of RestClient
    allow(RestClient).to receive(:post)
      .and_return({ error: 'invalid_grant' }.to_json)
    expect { chef_run }.to raise_error(Exception)
  end
end

azuredns/recipe/get_azure_token.rb

require 'rest_client'
require 'json'

cloud_name = node['workorder']['cloud']['ciName']
cloud = node['workorder']['services']['dns'][cloud_name]
dns_attributes = cloud['ciAttributes']

#  Establish connection and get a security token
token = azuredns_token 'azure_token' do
  tenant_id dns_attributes['tenant_id']
  client_id dns_attributes['client_id']
  client_secret dns_attributes['client_secret']
end

token.run_action(:retrieve)

azuredns/metadata.rb

name             'Azuredns'
maintainer       'Shaffan'
maintainer_email 'shaffan.chaudhry1@gmail.com'
license          'Apache License, Version 2.0'
description      'Installs/Configures Azure DNS'
version          '0.1.0'
depends          'azure'

Please help!

Unit Testing Order of Enum

I have an enum that is ordered, representing sections of a grocery store in the order I traverse them.

enum Departments { Produce=0, Bulk=1, Deli=2, Frozen=3, NonFood=4, Bakery=5, DryGoods=6 }

Now I have some class representing items to get that have a name and a department:

class GroceryItem : IComparable<GroceryItem>
{
    string Name;
    Departments Department;
}

the proper sorting function sorts the grocery list alphabetically by Department, so I can minimize my traversal of the store.

Would it be valuable to unit test this enum for order, or should I be using some other data structure to hold department?

Unit test in python using mock

I am developing a project in Python and want to write unit tests using 'mock'.

I have refered to http://ift.tt/1gYzMss

But I do not understand the concept very well. Can someone suggest where can I start with?

Unity - Unit Test Tools (Missing Fields in Assertion Component)

I have some experience working in Unity, but never anything as complex as using the Unit Test Tools. I'm trying that now. However, my version is missing certain fields present (and necessary) from the Unity tutorials currently available. I have completely deleted Unity and reinstalled. I have had friends install the same version of Unity and the Unit Test Tools on their comparable machines, and they get the results seen in the tutorials. I have searched and searched, but found no mention of this issue. Please help.

Below are two screen shots. The first is the version in the tutorials (the one I am trying to get). The second is how my setup has it. It's specific to the assertion component.

Desired Outcome

My unwanted version

python unittest mock can't handle partially qualified name

If I have two files with the following contents:

test_helper.py:

class Installer:
    def __init__(self, foo, bar, version):
        # Init stuff
        raise Exception('If we're here, mock didn't work')

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        # cleanup
        pass

    def install(self):
        # Install stuff
        raise Exception('If we're here, mock didn't work')

And test.py:

import unittest
from mock import patch
from test_helper import Installer

class Deployer:
    def deploy(self):
        with Installer('foo', 'bar', 1) as installer:
            installer.install()

class DeployerTest(unittest.TestCase):
    @patch('tests.test_helper.Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()
        mock_installer.assert_called_once_with('foo', 'bar', 1)

The code above doesn't test correctly. The mock is not applied properly:

  File "/Library/Python/2.7/site-packages/http://ift.tt/1LRgPTF", line 947, in assert_called_once_with
    raise AssertionError(msg)
AssertionError: Expected 'Installer' to be called once. Called 0 times.

If I make the following changes in test.py:

  1. Change from test_helper import Installer to import test_helper, and
  2. Change with Installer('foo', 'bar', 1) as installer: to with test_helper.Installer('foo', 'bar', 1) as installer:

The code then works. Why does the mock only apply when I use the fully qualified name? Is it supposed to work in the partially-qualified case?

Inheriting from unittest's TestCase - Python

I'm implementing a test automation framework. In order to make it customizable, I decided to inherit from unittest.TestCase:

import multiprocessing
import unittest
import logger
import credentials

class MyTestCase(unittest.TestCase):
    """
    An extention of the unittest's TestCase
    """
    __test__ = False # Important, makes sure tests are not run on base class

    def __init__(self, login_url=None,
                 *args, **kwargs):

        unittest.TestCase.__init__(self, *args, **kwargs)
        self.log = logger.logger
        # add a framework object for each test case.
        self.framework = None
        self.password = None
        self.credential = credentials.Credential()
        self.username = None
        self.login_url=login_url

    def do_work(self, func, args, callback, processes=1):
        """
        Perform a task asynchronously, in order to avoid delays or race conditions.

        Args:
            f: (function)
                pass a function object to the async call.
            args: (list)
                The arguments the function f take
            callback: (function)
                Where to return the method to, after completion.
            processes: (integer)

        Returns:
            The result of applying args to the function func.
        """
        try:
            pool = multiprocessing.Pool(processes=processes)
            result = pool.apply_async(func, args, callback)
            return result
        except Exception, e:
            self.log.exception(e)

before, I was passing methodName='runTest' however that was causing only def runTest(self) to be executed. A sample test is:

class SampleTest(MyTestCase):
    __test__ = True

    def __init__(self, *args, **kwargs):
       MyTestCase.__init__(self, *args, **kwargs)

    def setUp(self):
      # do some setting up here

    def runTest(self):
       self.test_a()
       self.test_b()

    def test_a(self):
       # to some testing A here

    def test_b(self):
       # to some testing B here

So the XML test-reports were only showing runTest() as executed. I want to modify that and since I don't need runTest() much, I would like to have test_a() and test_b() executing as standalone tests. However when I execute the code, I'm getting the following error:

2016-02-29 17:12:04 - ERROR - no such test method in <class 'testcases.sample_test.SampleTest'>: runTest
Traceback (most recent call last):
  File "sample_test.py", line 27, in __init__
    testcase.MyTestCase.__init__(self, *args, **kwargs)
  File "my_case.py", line 29, in __init__
    unittest.TestCase.__init__(self, *args, **kwargs)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 189, in __init__
    (self.__class__, methodName))
ValueError: no such test method in <class 'sample_test.SampleTest'>: runTest

Sure, adding methodName='runTest' to the MyTestCase constructor will fix that ... however that will not produce the result I want. How can I have it fixed?

Maven does not find unit tests to run, no Junit tests are executed Java

When run mvn clean install my project builds successfully howver it does not run any unit tests I have set up.

Here is the console output:

------------------------------------------------------- T E S T S

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] [INFO] --- exec-maven-plugin:1.1:exec (generate-output) @ print-engine-tester --- [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ print-engine---

Here is my pom:

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/HBk9RF">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.r.cg.fs.tools</groupId>
        <artifactId>tools</artifactId>
        <version>2.8.1-SNAPSHOT</version>
    </parent>

    <artifactId>print-engine-tester</artifactId>
    <name>FPS Print Engine (Regression) Tester App</name>

    <dependencies>
        <dependency>
            <groupId>com.r.cg.fs.common</groupId>
            <artifactId>build-utility</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.r.cg.fs.engines</groupId>
            <artifactId>print-engine</artifactId>
              <exclusions>
                <exclusion>
                  <groupId>org.testng</groupId>
                  <artifactId>testng</artifactId>
                </exclusion>
              </exclusions>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>test</scope>
        </dependency>



    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack-dependencies</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.r.cg.fs.content.ty13</groupId>
                                    <artifactId>fps-production-content-bundle</artifactId>
                                    <version>2013.42-SNAPSHOT</version>
                                    <type>zip</type>
                                    <outputDirectory>target</outputDirectory>
                                    <includes>**/*.*</includes>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>com.r.cg.fs.content</groupId>
                                    <artifactId>tt-production-content</artifactId>
                                    <version>2012.0.0-SNAPSHOT</version>
                                    <classifier>bin</classifier>
                                    <type>zip</type>
                                    <outputDirectory>target</outputDirectory>
                                    <includes>**/*.zip</includes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
                    <plugin>
              <groupId>org.codehaus.mojo</groupId>
              <artifactId>build-helper-maven-plugin</artifactId>
              <version>1.10</version>
              <executions>
                <execution>
                  <id>add-resource</id>
                  <phase>generate-test-resources</phase>
                  <goals>
                    <goal>add-test-resource</goal>
                  </goals>
                  <configuration>
                    <resources>
                      <resource>
                        <directory>${project.build.directory}/pdf-content</directory>
                        <!-- <targetPath>/pdf-content</targetPath> -->
                      </resource>
                    </resources>
                  </configuration>
                </execution>
              </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-output</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <configuration>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.1</version>
                <executions>
                    <execution>
                        <id>generate-output</id>
                        <phase>test</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                            <executable>java</executable>
                            <classpathScope>test</classpathScope>
                            <arguments>
                                <argument>-Dfps.root.dir=target/pdf-content</argument>
                                <argument>-classpath</argument>
                                <classpath />
                                <argument>PrintEngineTester</argument>
                                <argument>target/pdf-content</argument>
                                <argument>target/pdf-content/fonts</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <systemProperties>
                        <property>
                            <name>fileName</name>
                            <value>${fileName}</value>
                        </property>
                    </systemProperties>
                </configuration>
            </plugin>     
        </plugins>
    </build>

    <!-- Need "central" for resolving parent artifact -->
    <repositories>
        <repository>
            <id>central</id>
            <name>r Central Repository</name>
            <url>http://ift.tt/1OJXqnq;
            <snapshots>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </repository>
    </repositories>

</project>

How to test for multiple warnings in an unknown order using testthat?

I want to test that a function generates multiple warnings (4 or more), when the order of the warnings can vary. My best attempt to do this is based on look-ahead RegExp matching. Simplifying to just 2 warnings, I know my RegExp work on a single string output, because both of the following are true:

grepl("(?s)(?=.*2)(?=.*1)", "* warn 1.\n* warn 2.", perl=TRUE)
grepl("(?s)(?=.*1)(?=.*2)", "* warn 1.\n* warn 2.", perl=TRUE)

However, this does not work when testing multiple warnings with testhat::expect_warning

# The function generating warnings:
foo <- function() { warning("warn 1."); warning("warn 2.") }
foo()
Warning messages:
1: In foo() : warn 1.
2: In foo() : warn 2.

# Testing it
expect_warning( foo(), "(?s)(?=.*1)(?=.*2)", perl=TRUE)

Error: foo() does not match '(?s)(?=.*1)(?=.*2)'. Actual values:
* warn 1.
* warn 2.

I suspect this is because the internals of expect_warning are doing something like testing the given RegExp against each warning separately--why an expect_warning( ... all=TRUE ) parameter might be meaningful.

Unfortunately I can't use this with a RegExp like "1 | 2"; that succeeds if only one warning is given.

I also want to avoid running the function multiple times and testing a different warning each time. There is a large amount of setup and teardown code needed to test the real function. It interacts heavily with the file system, and since it is the file-system warnings I am testing for, I can't mock that. Moreover, I want to test for the warnings in multiple situations, each of which requires different setup and teardown code, so this quickly bloats my tests.

Any suggestion on how to test for multiple warnings simply and all at once?

Creating a stub of document.getSelection using Sinon

My function, which you can find below, uses document.getSelection to get the currently selected text on the screen. I need to be able to specify the value of document.getSelection so that I test my function.

I tried creating the stub like so:

document.getSelection = sinon.stub(document, "getSelection", function() { return "Hello world!" } );

var selection = wysiwyg.getCurrentRange();

However, It just get undefined for selection. Can someone tell me what I'm doing wrong?

Here's the method I'm testing:

 Wysiwyg.prototype.getCurrentRange = function() {
    var sel, range;
    if ( window.getSelection ) {
        sel = window.getSelection();
        if ( sel.getRangeAt && sel.rangeCount ) {
            range = sel.getRangeAt( 0 );
        }
    } else if ( document.selection ) {
        range = document.selection.createRange();
    }

    return range;
 };

how to load actual dependencies into a angularjs test with jasmine and karma

I have been looking around online, but seems, no one really injecting the actual dependencies into a unit test for angularjs using jasmine and karma...

I think there is definitely a separation of concern for the testing process, but I also would like to know how it integrated well with current dependencies in use... so just in case a dependencies is not working well with my component, I will be aware of it!

So, I wonder how can I inject the actual dependencies? So far I found online articles are all about mocking it with a fake one... But I want to use the actual one. Right now, when I enter karma start I am getting a error of Error: [$injector:unpr] Unknown provider: _Provider <- _ <-MyService

I inject services in forEach block like this beforeEach(angular.mock.inject(function(_MyService_) { I wonder if its because I am not using the fake service?

Any hint will help ia. Thanks!

describe('MyCtrl', function() {

  //Data Exposure Prep
  var $controller;
  var $rootScope;
  var $scope;
  var controller;
  var MyService;

  dd1 = {
    itinerary: globalMockData.d1,//I stored globalMockData somewhere else
  };

  beforeEach(angular.mock.module('myapp'));
  beforeEach(angular.mock.inject(function(_$rootScope_, _$controller_, _$httpBackend_) {
    $rootScope = _$rootScope_;
    $controller = _$controller_;
    $httpBackend = _$httpBackend_;
    $scope = $rootScope.$new();
    controller = $controller('MyCtrl', { $scope: $scope }, dd1);
  }));

  //BASIC INFO
  describe('should receive sth', function() {
    it('finds sth', function() {
      expect(controller.answer).toBeDefined();
    });
  });

});

`

Python how to write test driver?

import unittest
from test import support

class TestCase(unittest.TestCase):
    def addition():


x = [[3, 4],
     [5, 6]]

y = [[1, 2],
     [3, 4]]

output = [[0, 0],
          [0, 0]]

def addition(x, y):
for i in range(len(x)):
    for j in range(len(y[0])):
        output[i][j] += x[i][j] + y[i][j]

for o in output:
    print(o)

print("addition: ")
addition(x, y)

Hi, thanks for reading. I was trying to make a test driver for my matrix addition but I wonder if I was doing correctly. I added import unittest and from test import support at the top of the code. But do I have to make a new .py file in order to make test driver? How can I make a test driver for a matrix addition? I just started python a week ago. Please help!

Karma Jasmine Runs Test Three Times

I am running Karma/Jasmine/Angular 2.0 tests on my development box. Just recently, Karma on my development box decided to start running my tests three times. Yes, exactly three times, every time.

On the first run, everything passes as expected. However, on the second and third pass, all of the same things fail. It always acknowledges that there are 7 tests, but runs 21, and 10 fail (first-grade math out the window)????

This also fails on Travis with SauceLabs. (Note: That links to an older build with 3 tests, but ran 9, and 5 fail???)

I have a screenshot, karma.conf.js file, and one suite which started this whole thing. Any help with be greatly appreciated.


Culprit [TypeScript] (Remove this and problem solved on my dev box):

describe('From the Conductor Service', () => {
    let arr: Array<ComponentStatusModel> = null;
    let svc: ConductorService = null;

    beforeEach(() => {  
        arr = [/* Inits the array*/];
        svc = new ConductorService();
    });

    describe('when it is handed a container to hold objects which need loaded', () => {
        // More passing tests...

        /// vvvvv The culprit !!!!!
        describe('then when you need to access the container', () => {
            beforeEach(() => {
                svc.loadedContainer = arr;
            });

            it('it should always be available', () => {
                assertIsLocalDataInTheService(arr, svc.loadedContainer);
            });
        });
        /// ^^^^^ End of culprit !!!!!
    });

    // More passing tests...
});

Failing Tests:

Tests are ran three times

Simplified karma.conf.js:

module.exports = function (config) {
    config.set({
        autoWatch: false,
        basePath: '.',
        browsers: ['Chrome'],
        colors: true,
        frameworks: ['jasmine'],
        logLevel: config.LOG_INFO,
        port: 9876,
        reporters: ['coverage', 'progress'],
        singleRun: true,

        coverageReporter: {
            // Code coverage config
        },

        files: [
            // Loads everything I need to work
        ],

        plugins: [
            'karma-chrome-launcher',
            'karma-coverage',
            'karma-jasmine'
        ],

        preprocessors: {
            'app/**/*.js': ['coverage']
        },

        proxies: {
            // Adjust the paths
        }
    })
}

How to test service with a resource inside of it

So I have a fairly simple service function that takes a meeting resource, and decides if the user has permission to write to it based in the return status from the server. This works fine, but I am struggling with how to write the unit tests for it.

The service:

rmtg.service('share_manager', ['$log', function($log) {

...

    this.getWritablePermission = function (meeting, callback) {

        var originalTitle = meeting.Description;

        meeting.Description = 'getWritablePermission Test'

        meeting.$put().then(function (serverData) {
            meeting.Description = originalTitle;
            meeting.$put().then(function (serverData) {
                // sets isWriteable in scope to true
                callback(true);
            });
        }).catch(function (serverData) {
            callback(false);
        });
    };
 }]);

and the test so far:

describe("share_manager service", function(){
     beforeEach(module("rmtg"));

    var share_manager;
    beforeEach(inject(function(_share_manager_, _$httpBackend_){
        share_manager = _share_manager_;
        $httpBackend = _$httpBackend_;
    }));

    ...

    describe(".getWritablePermission", function () {
        var mockMeeting = {
            Description: 'Mock Title',
            $put: function(){
               return
            }
        };
        var mockCallback = function(){};
    });
});

Here is where I got stuck. How am I supposed to mock a promise like this? The Meeting is a resource that is defined somewhere else, and want to mock it for the purpose of the service test, so long as it returns a promise that I can then fail/succeed.

I looked at the $httpBackend service, but that doesn't deal with promises, and the Jasmine SpyOn documentation didn't seem to deal with it either.

Is there a way I can return a List of VO's by passing a VO using JMockit?

I am trying to get a List of VO's based on a search Criteria where I am passing a VO as an argument. For Example:

I am setting the values of a DummyVO and then passing that as an argument. Here is the complete code.

DummyVO dummyVO;
ActualVO actualVO;

@Before
public void setup(){
this.dummyVO.setId("1");
this.dummyVO.setVersion(2);

this.actualVO.set....
this.actualVO.set....

}

After this, I am trying to test If I am getting a list of VO's(at this point, just one VO). The search method runs a query behind the scenes( select * from VO where id = "");

@Test
public void testDAO() throws Exception{

List<ActualVO> mockVOList = compositeDAO.getSearchCriteria(this.dummyVO);

}

However its returning an empty list. I am not sure what's the problem. It is supposed to return the ActualVO. Please let me know if there is a better way to do this.

Thanks

visual studio team services build - How to specify different connection string for a Sql Server Test Project

I have a SQL Server unit testing project, the connection string for the database is located in the app.config file as follows

    <configuration>
    <configSections>
        <section name="SqlUnitTesting" type="Microsoft.Data.Tools.Schema.Sql.UnitTesting.Configuration.SqlUnitTestingSection, Microsoft.Data.Tools.Schema.Sql.UnitTesting, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </configSections>
    <SqlUnitTesting>
        <!--<DatabaseDeployment   DatabaseProjectFileName="..\..\..\AklAlbait.Database\AklAlbait.Database.sqlproj"
            Configuration="Debug" />-->
        <DataGeneration ClearDatabase="true" />
        <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=.;Initial Catalog=AklAlbait;Persist Security Info=True;User ID=sa;Pooling=False;Connect Timeout=30"
            CommandTimeout="30" />
        <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=.;Initial Catalog=AklAlbait;Persist Security Info=True;User ID=sa;Pooling=False;Connect Timeout=30"
            CommandTimeout="30" />
    </SqlUnitTesting>
</configuration>

Now when i try to create a build definition to run on VS team services (VSO), i need away to specify a different connection string to be used, how can i do this?? in the case of Team Foundation Server we can add another config file named "BuildComputer.app.config", where BuildComputer is the name of the computer on which your build agent runs. (http://ift.tt/1Lrh6BB). I need something that works on the online team foundation build.

groovy per instance metaClass method override doesnt work as expected in spock test

having a problem

I have a class with method called execute(). In some spock unit test i dummy out the execute method and give it a mock closure like this

def setup () {
    rule = new DynamicRule ()
}

def "test default execution " (){
    given : "basic AORule "
    def mockres
    rule.metaClass.execute = {-> mockres = "did nothing"}     //mock the action
    def res = rule.execute()


    expect : "execute should do nothing "
    mockres == "did nothing"

}

if i run this test it fails. in the idea editor it shows the mock closure as underlined. but the rule.execute() on the next line isnt - so it can see the method

if i change this test for this

    rule.metaClass.execute2 = {-> mockres = "did nothing"}     //mock the action
    def res = rule.execute2()

then the test passes.

outside of spock i just ran a simple groovy script and did the method overload and that works correctly as id expect and the method is mocked out with the closure

class A {
    def execute () {
        println "thing"
    }
}

def c = new A()
def res
c.execute()

c.metaClass.execute  = {-> res =2 ; println "modified thing "; }

c.execute ()

println "res = "+  res

why doesn't the same happen in the spock test ?

query - how do unit stub test a closure correctly for spock ?

this modified version of the test works successfully

def "test default execution " (){
    given : "basic AORule "

    def mockres

    def stub = new StubFor(AORule)
    stub.demand.execute { mockres = "did nothing" }
//        rule.metaClass.execute = {-> mockres = "did nothing"}     //mock the action
//        def res = rule.execute()

    expect : "execute should do nothing "
    stub.use {
        rule.execute()
        mockres == "did nothing"

    }
}

why didn't the simple per metaclass frig work in spock ? Something i'm not understanding here

Load Json Fixture in Karma/Mocha

I am using Karma with Mocha and karma-fixture. If I go into debug when I run tests, I can see the file is loaded in the server. If I changed the config included:true, then I can see it's loaded on the console. The extension is changed to .js (rather than .json) and if I view source on the file (in browser window) the json is wrapped in a function -- so it seems like everything is happening as described in the documentation. However, I get an error that the file cannot be found. I have included the relevant configs and errors below. Thank you!

The configuration:

The file is located here, pathed from root of my project: \test\fixtures\json-data\querybrowser.json

Karma

 files: [{pattern: 'test/fixtures/{,*/}*', watched: true, included: false, served: true}]

TEST spec

 fixture.setBase('base/test/fixtures/json-data');
 querybrowser_json = fixture.load('querybrowser.json');

The Error

 Chrome 48.0.2564 (Windows 7 0.0.0) Query Browser Function Tests "before all" hook FAILED
 ReferenceError: Cannot find fixture 'base/test/fixtures/json-data/querybrowser.js' 
 at Fixture._throwNoFixture (////node_modules/karma-fixture/lib/fixture.js:141:13)

load DRY test data object without use $httpBackend for angularjs unit test in jasmine

my unit test is for a directive's controller which does not rely on any external http calls. My several attempts on using the $httpBackend has failed ( read more than 10 articles about that $httpBackend)...

I wonder, if there is way to inject data synchronously into the my-test.spec.js file? the data not really need to be a json per say, since json needs to be converted into js objects anyway.

So far I tried to add 'spec/mock-data.js' (contains a global var mockData ={abc:"123"}), into karma.conf.js but seems my describe block's forEach section does not really see that global var and returns undefined

I wonder am I missing something here? if not, then is there a better way for me to injecting ready-to-use data rather than json, that so I can reusable throughout different spec files as if I would have loaded with $httpBackend?

I tried the way described here, but that's when I got undefined instead.

Verifying if a void method has been called using Moq

I have a class which is responsible for building PPT slides for exporting. To unit test this I have created an interface so it can be mocking using Moq; all great so far. However I run into difficulties when trying to test that my method has been called. It is a void method so at this point I only want to know that the method has been hit.

Here is my interface:

interface IPowerpointExporter
{
    void AddSlides(int amount);

    void setTitle(string title);
}

And here's my unit test:

[TestMethod]
public void testPPTObject()
{
    var mockPPT = new Mock<IPowerpointExporter>();
    mockPPT.Setup(m => m.AddSlides(1)).Verifiable();
    mockPPT.Object.AddSlides(1);
    mockPPT.VerifyAll();
}

However when I come to call AddSlides() I get a GeneratorException. The explanation for this is that my IPowerpointExporter was not accessible. I have a feeling this is because I am trying to call a method on an interface, though I'm unsure since I've got my object at mockPPT.Object.AddSlides(); at this point.

Note that I've also tried the following trying to use an actual object rather than Interface.Object. This also gives the same exception:

[TestMethod]
public void testPPTObject()
{
    var mockPPT = new Mock<IPowerpointExporter>();
    mockPPT.Setup(m => m.AddSlides(1)).Verifiable();

    ExportPowerPoint temp = (ExportPowerPoint)mockPPT.Object;
    temp.AddSlides(1);
    mockPPT.VerifyAll();
}

Using Moq how can I check that my method has been called? Is what I'm doing above along the right lines?

Functional testing framework

I have an application written in C++. I use the boost unit test framework to do my unit testing. I want to add some functional/end-to-end testing. My app essentially outputs a file, so I want to run the application with a few different inputs (command line arguments) and check the results by parsing the output file.

My first thought is to use python to automate these tests. I went through a reasonably exhaustive list and here's my top 3 at first glance:

  • unittest framework. Seems a valid option, but is it ok for functional/end-to-end testing?
  • nose. Seems good, but they clearly say it's not supported anymore, so I feel I should exclude it.
  • py.test. Seems fairly old, and less good than nose.

So after looking into this, I feel like unittest is the best framework for my use case. However, I have a nagging feeling that I might regret my decision. I think this is mainly because the framework is called "unittest"! Is it really restricted to unit test? Will I regret my decision some time down the road?

How to make test class read data from target/ and not target/test-classes Java

I have a Java project that when I build doing a mvn clean install command from the commandline, it generates an output target folder.

I have a Junit test class which takes it's test data from this target folder. When running this test class directly (right click Testclass.java > Run As > Junit Test) works fine since the target folder has already been generated.

However to when I do a mvn clean (which clears out the target folder and my test data as well) then do a mvn clean install I get a test failure. Because the test is trying to read from target/test-classes/pdf-content and not from target/pdf-content

How can I make my Testclass read test data from target/ and not target/test-classes ?

How can I get MSTest to create tests for all the methods in a project?

When I created a new project in my solution, it created a class in my Test project like this:

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

namespace AYttFMScheduler.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
        }
    }
}

Then I thought I should be able to generate test methods corresponding to all the methods in my main project, but when I right-clicked a method in my main project and selected "Create Unit Tests" it generated this separate file in my Test project (after I selected the existing test project in the dialog) with only one test method, for the method I right-clicked, generated:

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

namespace AYttFMScheduler.Tests
{
    [TestClass()]
    public class AYttFMConstsAndUtilsTests
    {
        [TestMethod()]
        public void SerializeStudentsFileTest()
        {
            Assert.Fail();
        }
    }
}

First, I wonder why the vast difference between the two? The creation of the method corresponding to the one I right-clicked (SerializeStudentsFileTest) makes sense, as does the default code within that test method (Assert.Fail()), but why the superfluous parens appended to "TestClass" and "TestMethod"?

Besides that oddity, and of primary concern to me, is that I think there should be an option when selecting "Create Unit Tests" to create them for the entire class, and even for the entire project. Surely there is a way, although I could not suss it out or google it to the fore.

Mocked private method is called

I'm using PowerMockito for mocking private method. But instead being mocked it is called. I need to test strangeMethod(), which calls privateMethod().

Here is my class for testing:

public class ExampleService {
public String strangeMethod() {
        privateMethod();
        return "Done!";
    }

    private String privateMethod() {
        throw new UnsupportedOperationException();
    }
}

My test method:

@Test
    public void strangeMethodTest() throws Exception {
        ExampleService exampleService = PowerMockito.spy(new ExampleService());
        PowerMockito.when(exampleService, "privateMethod").thenReturn("");
        exampleService.strangeMethod();
    }

As a result of the test I'm getting UnsupportedOperationException. This means, that privateMethod() is called.

View model to domain model, where to test the mapping?

I'm currently experimenting with a mapping framework (automapper-like) in a MVC project.

In my controller I map the view model to the domain model (seems like the legit place to do it) using the extensions method "Map" of the framework.

Of course my code won't work if the mapping break (for instance if some property name change and causes mismatch).

But where to test the mapping work as expected?

The controller isn't the "unit" responsible of that. Neither is the View Model nor the Domain Model.

I though I could create my own wrapper (Ioc injectable instance) and unit test it with the mapping of view model to domain model bu it feels kinda awkward (how could code readers know those test need to be performed on specific classes?).

I'm kinda lost.

object reference not set to an instance when functions call in unit test(intellitest)

i have problem when i call any function within my unit test controller class, when i run the test, its give error

Object reference not set to an instance of an object

i am not sure what i am missing here or i do not know i do call function in unit test, i am using intellitest using visual studio 2015 enterprise edition

here my code

  1. /// This class contains parameterized unit tests for AccountFinFilesController

    [TestClass]
    [PexClass(typeof(AccountFinFilesController))]
    [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
    [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
    public partial class AccountFinFilesControllerTest
    {
    
        /// <summary>Test stub for .ctor(ISmallBizRepository)</summary>
        [PexMethod]
        public AccountFinFilesController ConstructorTest(ISmallBizRepository repo)
        {
            AccountFinFilesController target = new AccountFinFilesController(repo);
            return target;
            // TODO: add assertions to method AccountFinFilesControllerTest.ConstructorTest(ISmallBizRepository)
        }
    
        /// <summary>Test stub for Delete(Guid, Guid)</summary>
        [PexMethod]
        public HttpResponseMessage DeleteTest(
            [PexAssumeUnderTest]AccountFinFilesController target,
            Guid id,
            Guid deletedby
        )
        {
            HttpResponseMessage result = target.Delete(id, deletedby);
            return result;
            // TODO: add assertions to method AccountFinFilesControllerTest.DeleteTest(AccountFinFilesController, Guid, Guid)
        }
    
        /// <summary>Test stub for GetAccountFinFilesTable(Guid, Guid)</summary>
        [PexMethod]
        public IQueryable GetAccountFinFilesTableTest(
            [PexAssumeUnderTest]AccountFinFilesController target,
            Guid firmid,
            Guid id
        )
        {
            IQueryable result = target.GetAccountFinFilesTable(firmid, id);
            Assert.IsNotNull(result);
            return result;
            // TODO: add assertions to method AccountFinFilesControllerTest.GetAccountFinFilesTableTest(AccountFinFilesController, Guid, Guid)
        }
    
        /// <summary>Test stub for GetAccountFinFilesTable(Guid)</summary>
        [PexMethod]
        public IQueryable GetAccountFinFilesTableTest01([PexAssumeUnderTest]AccountFinFilesController target, Guid firmid)
        {
    
            IQueryable result = target.GetAccountFinFilesTable(Guid.Parse("75165ae3-cbae-e511-b0bf-00259076695a"));
            Assert.IsNotNull(result);
            return result;
            // TODO: add assertions to method AccountFinFilesControllerTest.GetAccountFinFilesTableTest01(AccountFinFilesController, Guid)
        }
    
        /// <summary>Test stub for Post(AccountFinFilesTable, Guid, Guid)</summary>
        [PexMethod]
        public HttpResponseMessage PostTest(
            [PexAssumeUnderTest]AccountFinFilesController target,
            AccountFinFilesTable obj,
            Guid firmid,
            Guid createdby
        )
        {
            HttpResponseMessage result = target.Post(obj, firmid, createdby);
            return result;
            // TODO: add assertions to method AccountFinFilesControllerTest.PostTest(AccountFinFilesController, AccountFinFilesTable, Guid, Guid)
        }
    
        /// <summary>Test stub for Put(AccountFinFilesTable)</summary>
        [PexMethod]
        public HttpResponseMessage PutTest([PexAssumeUnderTest]AccountFinFilesController target, AccountFinFilesTable obj)
        {
            HttpResponseMessage result = target.Put(obj);
            return result;
            // TODO: add assertions to method AccountFinFilesControllerTest.PutTest(AccountFinFilesController, AccountFinFilesTable)
        }
    }
    
    
  2. WebAPI controller class

      public class AccountFinFilesController : BaseApiController
      {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public AccountFinFilesController(ISmallBizRepository repo)
            : base(repo)
        {
        }
    
        // GET api/AccountFinFiles
        /// <summary>
        /// GetAccountFinFilesTable
        /// </summary>
        /// <param name="firmid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IQueryable GetAccountFinFilesTable(Guid firmid, Guid id)
        {
            log.Info("GetAccountFinFilesTable API -- firmid=" + firmid + "&id=" + id);
            return TheRepository.GetAccountFinFile(firmid, id);
        }
    
        /// <summary>
        /// GetAccountFinFilesTable
        /// </summary>
        /// <param name="firmid"></param>
        /// <returns></returns>
        [HttpGet]
        public IQueryable GetAccountFinFilesTable(Guid firmid)
        {
                log.Info("GetAccountFinFilesTable API -- firmid=" + firmid);
                return TheRepository.GetAccountFinFile(firmid);
        }
    
        /// <summary>
        /// update AccountFinFilesTable
        /// </summary>
        /// <param name="account_finfilestabledm"></param>
        /// <returns></returns>
        [HttpPut]
        public HttpResponseMessage Put(AccountFinFilesTable obj)
        {
            try
            {
                var updatedEntity = TheModelFactory.Parse(obj);
    
                if (updatedEntity == null)
                {
                    log.Error(MessagesHelper.recordnotfound + "File_ID: " + obj.File_ID);
                    Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read AccountFinFilesTable from body");
                }
    
                var originalEntity = TheRepository.GetAccountFinFileByPrimaryKey(obj.File_ID);
    
                if (originalEntity == null || originalEntity.File_ID != obj.File_ID)
                {
                    log.Error(MessagesHelper.recordnotfound + "File_ID: " + obj.File_ID);
                    return Request.CreateResponse(HttpStatusCode.NotModified, "AccountFinFilesTable record not found");
                }
                else
                {
                    updatedEntity.File_ID = obj.File_ID;
                }
    
                if (TheRepository.Update(originalEntity, updatedEntity) && TheRepository.SaveAll())
                {
                    log.Info(MessagesHelper.updatesuccess + "File_ID: " + obj.File_ID);
                    return Request.CreateResponse(HttpStatusCode.OK, TheModelFactory.Create(updatedEntity));
                }
                else
                {
                    log.Error(MessagesHelper.updateerror + "File_ID: " + obj.File_ID);
                    return Request.CreateResponse(HttpStatusCode.NotModified, "Could not update to the database.");
                }
    
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + " " + obj.File_ID);
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
    
        }
    
        /// <summary>
        /// add new record to AccountFinFilesTable
        /// </summary>
        /// <param name="account_finfilestabledm"></param>
        /// <param name="firmid"></param>
        /// <param name="createdby"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Post(AccountFinFilesTable obj, Guid firmid, Guid createdby)
        {
            try
            {
                obj.FirmId = firmid;
                obj.ClientId = createdby;
                obj.CreatedDate = DateTime.UtcNow;
    
                var entity = TheModelFactory.Parse(obj);
    
                if (entity == null)
                {
                    log.Error(MessagesHelper.recordnotfound + " " + firmid + " " + createdby);
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read AccountFinFilesTable from body");
                }
                else
                {
                    if (TheRepository.Insert(entity) && TheRepository.SaveAll())
                    {
                        log.Info(MessagesHelper.savesuccess + " " + firmid + " " + createdby);
                        return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(entity));
                    }
                    else
                    {
                        log.Error(MessagesHelper.saverror + " " + firmid + " " + createdby);
                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to the database.");
                    }
                }
    
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + " " + firmid + " " + createdby);
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    
        /// <summary>
        /// delete record from AccountFinFilesTable
        /// </summary>
        /// <param name="account_finfilestabledm"></param>
        /// <param name="deletedby"></param>
        /// <returns></returns>
        [HttpDelete]
        public HttpResponseMessage Delete(Guid id, Guid deletedby)
        {
            try
            {
                var entity = TheRepository.GetAccountFinFileByPrimaryKey(id);
    
                if (entity == null)
                {
                    log.Error(MessagesHelper.recordnotfound + "File_ID: " + id);
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }
    
                if (TheRepository.DeleteAccountFinFile(id, deletedby) && TheRepository.SaveAll())
                {
                    log.Info(MessagesHelper.deletesuccess + "File_ID: " + entity.File_ID);
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    log.Error(MessagesHelper.deleteerror + "File_ID: " + entity.File_ID);
                    return Request.CreateResponse(HttpStatusCode.BadRequest, "Could not delete the record.");
                }
    
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "File_ID: " + id);
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
            }
    
        }
    
    }
    
    
  3. error

object reference not set to an instance of an object

please help/guide or provide me a complete solution according to my scenario, i will provide more detail if required. thanks for your valuable time and effort.

Get soap u i request from file system

i am completely a newbie to soap ui. I have a requirement where an xml is stored in my file system and i have to read that into my soap request and send it. I dint find any proper docs on this. I want to know if is this possible and how can i do this? Thanks in advance.

Detach ZF2 event listener during unit tests

I have an event listener set up in the module (it checks user permissions) in the onBootstrap method:

// attach permission listener to route event
$eventManager = $e->getApplication()->getEventManager();
$sm = $e->getApplication()->getServiceManager();
$permissionsListener = $sm->get('MyModule\Listener\Permissions');
$permissionsListener->attach($eventManager);

It works OK in the normal application.

For the unit tests, it would be great if I could disable this permission system to easily check that all pages are working correctly without worrying about setting up a fake admin user.

But I don't know how to do it.

In my test, which extends AbstractHttpControllerTestCase, I have done something like this:

// detach permission listener to route event
$sm = Bootstrap::getServiceManager();
$eventManager = $this->getApplication()->getEventManager();
$permissionsListener = $sm->get('MyModule\Listener\Permissions');
$permissionsListener->detach($eventManager);

But this doesn't disable the permission system. How can this be done?

unit testing of directive with default scope

I am trying to unit test a directive which has default scope(scope:false) but I am not able to inject dependency of its controller.

var MyApp = angular.module('MyApp',['MyDirectives','MyServices','MyControllers']);

Here is the directive

var MyDirectives = angular.module('MyDirectives', []);
MyDirectives.directive('myAddress', [ '$timeout', function ( $timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }

            elm.on('focus', function () {
                scope.AppData.ShowSeparateAddress = false;
            });

        }
    };
}]);

Here is my controller

var  MyControllers = angular.module(' MyControllers', []);
MyControllers.controller('Step1', [
'$rootScope', '$scope', 'AppData', function ($rootScope, $scope, AppData) {
  $scope.AppData = AppData.get();
   }

Here is my App Service

var  MyServices = angular.module(' MyServices', []);
    MyServices.factory('AppData', [function () {
    var data;
    return {
        get: function () {
            data = data || {};
            return data;
        }
    };
   }]);

Here is the unit test for address directive

beforeEach(module(MyApp));


var element, compiledElement, directiveElement;
var scope, compile, ele,AppData,controller;

beforeEach(inject(function(_$rootScope_, _$compile_){
scope = _$rootScope_.$new();
compile = _$compile_;
}));
 beforeEach(inject(function( _$controller_, _AppData_){

    AppData = _AppData_;
    controller = _$controller_('Step1',{scope:scope, AppData:AppData});
 }));
 function getCompiledElement(ele) {
     element = angular.element(ele);
     compiledElement = compile(element)(scope);
     scope.$digest();
     return compiledElement;
  }
it('should set show separate addrress as false when focussed',function(){
    ele = '<input type="text" data-my-address />';
    directiveElement = getCompiledElement(ele);
    console.log( directiveElement);
  expect( scope.AppData.ShowSeparateAddress ).toBe(false);
});

}); I get this following error

Error: [$injector:unpr] Unknown provider: AppDataProvider <- AppData

I have also trieed mocking the service through provide but it did not work Any help or idea ??

How to automatically export .trx file into testresult folder?

Currently my TestResult folder only contains Build files (.dll's and .exe) with debugging files (.pdb's). Such file(.trx) that would contain test results does not exist in the folder. I am using Visual Studio 2015 professional edition. Question: How do I automatically include test information file into TestResults folder for each unit test run?

can ProviderTestCase2, for testing content provider, be used in local unit test

Hi i know the android documentation says to run ProviderTestCase2 as instrumentation but was wondering if it is possible to run as a local unit test on my local computer? I built one as a "unit test"(as opposed to instumentation test) but getMockContentResolver() returns null. has anyone succeeded doing this? is it possible?

Skip host plugin activation with Tycho Surefire

I have a plugin project and a test fragment for it. Product is built using Tycho. My classes under tests are completely mocked. When I run tests I can see the host plugin is being activated (I have a start server logic in the start() method). I don't need to activate the host plugin and thus start the server when running unit tests.

Is this possible to run Tycho tests without starting the entire OSGI environment?

Spock: is it possible to specify where to create tempDir?

There is a useful annotation @TempDir in spock which helps us to create temporary folder and automatically delete it. Full name of annotation class looks like:

com.github.goldin.spock.extensions.tempdir.TempDir

It usually create temp folder in the folder which is defined as TMP environment variable. A question is: is it possible to specify folder where to create temp folder somehow?

Rails Minitest not executing last assertion

This is my test:

require 'test_helper'

class ProvinceTest < ActiveSupport::TestCase
  def setup
    @country = Country.find_by_iso("AO")
  end

  test "name has to be unique for its country" do
    exception = assert_raises(RecordInvalid) { @country.provinces.create!(name: "Luanda") }
    assert_equal "Has to have unique name for its country", exception.message
  end
end

The problem I'm having is that assert_equal "Has to have unique name for its country", exception.message it's not being executed (I know because I tried to execute a several commands between both assertions and they're not executed. However, whatever I put before the first assertion it will be executed.

What happens and why the test doesn't execute the second assertion?

I followed this question to build the test: Rails ActiveSupport: How to assert that an error is raised?

JUnitParams - executing method before test

@RunWith(JUnitParamsRunner.class)
public class MySimpleTest {

    private MyRec rec;
    private Matrix matrix;

    @Before
    public void createRecognizerBeforeEveryExecution() {
        rec = new MyRec();
        matrix = MatrixUtils.createMatrixWithValues();
    }

    public static Iterable<Object[]> data() {
        return Arrays.asList(
                new Object[]{"expectedvalue1", "input1"},
                new Object[]{"expectedvalue2", "input2"}
        );
    }

    @Test
    @Parameters(method = "data")
    public void test1(String output, String input) {
        rec.fun1(matrix);
        assertEquals(output, rec.someFunction(input));
    }

    public static Iterable<Object[]> data2() {
        return Arrays.asList(
                new Object[]{"expectedothervalue1", "input1"},
                new Object[]{"expectedothervalue2", "input2"}
        );
    }

    @Test
    @Parameters(method = "data2")
    public void test2(String output, String input) {
        rec.fun1(matrix);
        rec.fun2(matrix);
        assertEquals(output, rec.someFunction(input));
    }

}

I'm trying to find out what is the proper way to make this test. I'd like to use parametrized test, because it's really convenient way.

So as you can see, in every test function I call some function (fun1 and fun2). But I need to call it only once per every test (e.g. before each parametrized test execution).

Is there any way to tell JUnitParams that it should execute other function before executing all of parametrized tests?

I can't use @Before annotation, because as you can see in test1 I'm not using fun2. It think it should be executed by separate function.

Change mocked getResponse .net

I have a test that get some devices states from an endpoint. I have that response mocked and get the info correctly. The test that I want to implement must get this info and after a while get that info again and check if it's different to throw an event. The problem is that I can't change the mocked response in my test. This is what I tried.

Implementation of mocked WebRequest.

class TestWebRequestCreate : IWebRequestCreate
{

    public TestWebRequest testWebRequest { get; set; }

    public WebRequest Create(Uri uri)
    {
        WebRequest webRequest;
        if (testWebRequest == null)
        {
            webRequest = new TestWebRequest(HttpStatusCode.OK, "Testing response");
        }
        else
        {
            webRequest = testWebRequest;
        }
        return webRequest;
    }
}

class TestWebRequest : WebRequest
{
    public HttpStatusCode httpStatusCode { get; set; }
    public Stream responseMessage;

    /// <summary>
    ///  Initialize a new instance of <see cref="TestWebRequest"/>
    ///  with the response to return
    /// </summary>
    public TestWebRequest(HttpStatusCode httpStatusCode, string responseMessage)
    {
        this.httpStatusCode = httpStatusCode;
        this.responseMessage = StreamFromString(responseMessage);

    }

    public override WebResponse GetResponse()
    {
        MemoryStream responseCopy = new MemoryStream();
        //Stream responseCopy = new MemoryStream();
        responseMessage.Position = 0;
        responseMessage.CopyTo(responseCopy);
        //Reset position after reading Streams
        responseCopy.Position = 0;
        Mock<HttpWebResponse> mockHttpWebResponse = new Mock<HttpWebResponse>();
        mockHttpWebResponse.Setup(r => r.StatusCode).Returns(httpStatusCode);
        mockHttpWebResponse.Setup(r => r.GetResponseStream()).Returns(responseCopy);
        return mockHttpWebResponse.Object;
    }  

After this in my test I do this:

        public void DeviceChangedEvent_WhenDeviceHaveChanged_EventIsThrown()
    {
        string uri = new UriBuilder(TESTHOSTPREFFIX, TESTCORRECTHOST, TESTPORT, TESTDEVICEENDPOINT).ToString();
        bool wasThrown = false;
        m_deviceRetriever.Init(m_serviceProvider);
        m_deviceRetriever.Start();
        m_deviceRetriever.DeviceChangeEvent += (DeviceRetrieverOnDeviceChangeEvent, args) =>
        {
            wasThrown = true;
        };

        Thread.Sleep(5000);

        //Change device XML to simulate the change
        var namespaceManager = new XmlNamespaceManager(m_correctMockedXmlDevice.NameTable);
        namespaceManager.AddNamespace("ps", "http://ift.tt/1SbRASq");
        XmlNode printheadIdNode = m_correctMockedXmlDevices.SelectSingleNode("/ps:DevicesStatus/DeviceSlotCollection/DeviceSlot/SlotId", namespaceManager);
        deviceIdNode.InnerText = "Changed";
        m_testWebRequestCreateCorrectDevices = null;
        m_testWebRequestCreateCorrectDevices = new TestWebRequestCreate
        {
            testWebRequest = new TestWebRequest(HttpStatusCode.OK, m_correctMockedXmlDevices.InnerXml)
        };

        Thread.Sleep(5000);

        //We give some time to get the new state of printheads
        Assert.IsTrue(wasThrown);
    }
}

Before the test I'm preparing it creating this

    private void CreateCorrectDevicesMockEndpoint()
    {
        string uri = new UriBuilder(TESTHOSTPREFFIX, TESTCORRECTHOST, TESTPORT, TESTPRINTHEADSENDPOINT).ToString();
        m_testWebRequestCreateCorrectDevices = new TestWebRequestCreate();
        m_correctMockedXmlDevices = new XmlDocument();
        m_correctMockedXmlDevices.Load("pathToXMLFile");
        m_testWebRequestCreateCorrectDevices.testWebRequest = new TestWebRequest(HttpStatusCode.OK, m_correctMockedXmlPrintheads.InnerXml);
        WebRequest.RegisterPrefix(uri, m_testWebRequestCreateCorrectDevices);
    }

I'm not getting any error, the problem is that the XML returned by my mock is not changed. Thank you for your help!

React testing componentWillReceiveProps

I do quite a lot of component testing with React. Finally, I'm switching between DOM (renderIntoDocument) and Shallow rendering and I have two questions:

  • why componentDidMount is not triggered in Shallow rendering?
  • is it possible to trigger componentWillReceiveProps with DOM approach?

Thanks

What is best practice for unit testing multiple cases?

What is best practice for unit testing: include all the cases for the method in one unit test or break them out into separate ones?

Say I have

public int divideTwoInts(int a, int b){...}

And my default test case makes sure that

//Default Case

@Test
public testDivideTwoInts(){ 

int a = 6;
int b = 3;

int result = 2;
int expResult = divideTwoInts(a, b);

assertEquals(result, expResult);}

so far so good... but, say I want to make sure I handle division by zero - ie testing boundary and bad input cases.

Would I add it as a new unit test as in:

@Test
public testDivisionByZero_DivideTwoInts(){...}

OR as just another batch of code in my existing test?

(Also apologies if this has already been asked - coudn't find it)

Use Boost unit test framework for regression testing

I use the boost unit test framework to test a codebase. I want to add some regression testing. I am considering a shortcut which would be to use the unit test framework, add a "regression_test_suite" test suite, and implements my regression tests there. That would save me from having to manage another test framework.

Is it acceptable, or I am in danger of regretting badly that decision down the road? Or maybe missing on some really critical feature by not using directly a proper regression testing framework?

java.lang.Exception: No runnable methods (Junit)

I am using Junit 4.11 and intellij. I have two test classes that I want to run them through suite, however I get the no runnable methods exception.

Here are the test classes:

public class TrackingServiceTest {

    private TrackingService service;

    @Before
    public void setUp(){
        service = new TrackingService();
    }

    @Test
    public void NewTrackingServiceTotalIsZero() {
        assertEquals("tracking service total was not zero", 0, service.getTotal());
    }

    @Test
    public void WhenAddingProteinTotalIncreasesByThatAmount(){
        service.addProtein(10);
        assertEquals("protein amount was not correct", 10, service.getTotal());
    }

    @Test
    public void WhenRemovingProteinTotalRemainsZero(){
        service.removeProtein(5);
        assertEquals("Total suppose to be zero after removing protein",0, service.getTotal());
    }
    @Test (expected = InvalidGoalException.class)
    public void WhenGoalIsSetToLessThanZeroExceptionIsThrown() throws InvalidGoalException {
        service.setGoal(-5);
    }

    @Test (timeout = 100)
    @Ignore
    public void BadTest(){
        for(int i=0; i<100000000; i++)
            service.addProtein(i);
    }
}

And here is another sample test class just to check suite:

public class HelloJUnitTest {

    private TrackingService service;

    @Before
    public void setUp(){
        service = new TrackingService();
    }

    @Test
    public void NewTrackingServiceTotalIsZero() {
        assertEquals("tracking service total was not zero", 0, service.getTotal());
    }
}

And this is my suite class:

@RunWith(Suite.class)
@Suite.SuiteClasses(value = {
        TrackingService.class,
        HelloJUnitTest.class
})
public class ProteinTrackerSuite {

}

Does Arquilian Warp support Unit Testing JSF 1.2

This is my first shot at unit testing a JSF 1.2 + RichFaces 3.3.3 application; going through available frameworks, I found out about JSFUnit which should work with this JSF version, but later on discovered that this project is now discontinued and replaced with Arquilian Warp (which works with other related components).

However, due lack of documentation, I couldn't figure out if Arquilian Warp supports JSF 1.2; so can anyone answer, can I go ahead with it, or is JSFUnit my only option for the moment ?

How can I run test by JUnit4, with more threads?

I have a unit test class, and execute test with Spring JUnit4. All tests execute about 15 minutes, because test runs one by one. Here is my problem. This test we won to execute for continuing integration. After every commit we need to wait this 15 minutes, and this is not acceptable. How can we execute this test with more than one thread, or all tests execute in parallel?

Boost unit test framework: include main function of my codebase

I have a codebase on which I want to perform tests. One of the files of this codebase contains code that I want to test, in addition to the main function of the program.

When I add this file to my CMakeLists, it complains about the inclusion of multiple main functions.

Here's how things look:

RunTest.cpp:

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>

MyTest1.cpp:

#define BOOST_TEST_MODULE test_1_module
#define BOOST_TEST_DYNAMIC_LINK
#include <boost/test/unit_test.hpp>
#include <boost/test/parameterized_test.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/results_collector.hpp>

#include "../MyCode.h"

BOOST_AUTO_TEST_SUITE(test_suite_one)

BOOST_AUTO_TEST_CASE {
...
}

BOOST_AUTO_TEST_SUITE_END()

Here's what my CMakeLists look like:

SET (
    TestRunner

    RunTest.cpp
    MyCode.cpp #contains a main function
)

ADD_EXECUTABLE(TestRunner $TestRunner)

How can I solve this? Is there any way to ask boost to ignore the main function in my codebase?

C++ code coverage on Windows

I develop a C++ project under Windows that is compiled and linked into a static library.

For unit testing I use Catch. I develop my tests in a separate project and throw in the necessary headers and the .lib file from the main project. The tests then become an executable that I can run from the command line after the build process.

What I am missing is some code coverage report. I found a few code coverage tools for C++ online, but a lot seem to work with Linux only. Also I am not sure how to integrate them in my static library/exe build. As the library project needs to compile on Linux aswell, I would prefer a platform independent solution.

Is there a C++ code coverage tool that works on both Windows and Linux (preferrably without having to use a fixed IDE) and which can be integrated into my Catch unit tests workflow?

It is fine if I have to compile/link in some special way in order to be able to run the tests and get coverage.

$httpBackend is not working with angular-oauth in Karma+Jasmine+AngularJS environment

I have injected "angular-oauth2" in my module. "OAuth" is an provider of "angular-oauth2" module. I have written a new service "OauthSupport" in my module and injected the "OAuth" in to my service. I am calling functions(getAccessToken,getRefreshToken,revokeToken) of "OAuth" from my service.

Its working fine. Only problem is with unit-testing.

While calling the function "getAccessToken" a post call sent to the URL "http://localhost:3000/oauth/token" from "angular-oauth2" and data received from server.

My unittest call the function from my service myService.AccToken(props), this function calls the "getAccessToken" method from "OAuth" and makes post call. So I wrote mock for $http like as below

beforeEach(inject(function($injector) {
      $httpBackend = $injector.get('$httpBackend');
      $httpBackend.when('POST', 'http://localhost:3000/oauth/token').respond({
       errorCode: 'OK'
      }); 
});

But its not working, I am not getting response and done() function not get called. Finally getting error like as

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

I have some other services which makes post and get calls, I wrote unit testing and testcases are got succeed with the same $hhtp($httpBackend) mock object. Only for this service am getting error. Please someone help me to fix this Issue. Thanks in advance.

dimanche 28 février 2016

How to mock variable in directive unit test?

I have created a custom directive and would like to mock out a variable to make the test working. This is part of the unit test:

it('should pass on initialvalue', function() {
    scope.$apply(function() {
      scope.initial = 2;
      scope.Repairer = null;
    });
    expect(elementScope.initial).toEqual(2);
  });

The directive is calls a service when the initial-variable is set. Both tests are failing because in the directive I have a variable called request that is not properly mocked. The question is how can I mock this out? Or do I need to put the request variable on scope? This is part of the code:

 if (scope.Repairer) {

                        console.log('calling scriptservice');
                        var request = {
                            allocationProcess: (scope.$parent.lodgement.searchSettings.automatic.visible) ? 'automatic' : 'direct',
                            allocationSource: 'internal',
                            brand: brandScriptTag, // lookup brand scripting name
                            includeSegment: false,
                            relationship: scope.repairer.relationshipCode,
                            ruralSearch: scope.repairer.isRural,
                            state: scope.$parent.lodgement.claimLocation

                        };
                        scriptingService.getScript(request).then(function (scripts) {
                            scope.scripts = scripts;
                        });
                    } else {
                        scope.scripts = null;
                    }

plunker ref:http://ift.tt/1n9GTmp

AngularJS unit test pascalprecht.translate not available

Uncaught Error: [$injector:nomod] Module 'pascalprecht.translate' 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/13Se6sU$injector/nomod?p0=pascalprecht.translate (anonymous function)
(anonymous function)
ensure
module
angular.module
(anonymous function)
(anonymous function)
(anonymous function)

I have included in the index.html : '../js/angular-translate/*.js',

and in app.module : angular.module('app name', [..,'pascalprecht.translate',])

database operations as a pre-requisite to unit tests?

How do I create a unit test that partially makes use of database unit tests but is called from a regular unit test?

Yes, perhaps they may not be unit tests; you may wish to call them integration tests. Regardless of what you would like to label them, they are tests.

Within my nunit tests, I am using helper constants:

private const string NumericSerial="123123";
private const string NonNumericSerial="123123 bad serialnumber";
private const int ValidPatientId=123;
private const int InvalidPatientId=-1;
private const int PatientIdThatDoesNotExistInppp=111291;
private const string SerialNumberThatDoesNotExistInshmk="123123";
private const string SerialNumberThatDoesExistInshmk="1015873";
private const byte InvalidFirmwareVersion=0;
private const int FacilityThatDoesntExistInAAA=Int32.MaxValue;

Prior to running any tests that make use of these constants, I would like to verify that these constant are correctly defined.

For example I can Assert that NumericSerial is indeed numeric without having to do any mocking or injecting of any dependencies - I would simply tryparse it.

However, other constants such as PatientIdThatDoesNotExistInppp will need to be verified that it indeed does not exist in the ppp database. In order to do this, I can follow several routes:

  1. Implement a linq query within entity framework
  2. Explicitly send a select statement to the database
  3. Or I could a database unit test by first creating the necessary record (in our case it would make sure that 111291 does not exist in the database.

Unless you advise strongly against option #3, I am inclined to implement that. How do I create a unit test that partially makes use of database unit tests but is called from a regular unit test?

I am looking for something like the following:

[Test]
public response_from_database_unit_test_equals_111291()
{
//call the database unit test
//retrieve value from database unit test
}

How to mock the http connection error in $http unit testing in angular

Is there a way to simulate a connection error in an AngularJS unit test? I'm currently using jasmine and I mock connections to my service using $httpBackend. I know I can force a specific response code (such as 500) for a specific test if I want to simulate a service error. But I want to simulate a connection error, in order to test the "catch" part of the $http promise.

An example of the code I'd like to test:

  var getItemList = function() {
    return $http.get(API_BASE_URL + '/api/items')
      .then(function(response) {
        //I would check the response code and handle service errors here
        return response.data;
      })
      .catch(function() {
        return []; //I want to test the code I place in this catch
      });
  };

Is there a way to do that?

Unittest of an encryption code

Ok, so i believe i am missing something really obvious, but i have been trying for a long time to figure out a way and everyone who has tried to help me just tell me that i pretty much got it set up correctly for everything to work, but it doesn't no matter what test i try, i have been through so many but the most promising for now is

import unittest
from unittest import TestCase
from mock import patch
from encrdecrprog import encryption
class teststuff(TestCase):
    def test_encryption(self):
        with patch('__bulletin__.raw_input', return_value = 'x') as raw_input:
            self.assertEqual(encryption(x), '78')
            _raw_input.assert_called_once_with('x')

at least there is no errors, but i don't know where to go from now and i don't really get a measure on what works or how it works. I stole this from python mocking raw input in unittests I just don't understand how it works, at all...

The code that i want to test is

def enprint():

    print(encryption(raw_input()))
def encryption(x):

    pur = ("".join("{:02x}".format(ord(c)) for c in x)) 
    #The code for this was shamelessly stolen from http://ift.tt/1GkMMVC

    return pur
def main():
    userinput = raw_input()    
    if userinput == "1":
        enprint()    

I gutted my code to get this, but that should be the most important things for my question. I want to unittest encryption(x), which basically means i want to test if x = 78 (or anything else is their corresponding hexadecimals, i don't really care as long as the answer is what i expected-.-), i also have to use the unittest package because school reasons... I believe this has been answered before, but because i can't comment due to lack of reputation i can't really ask when i don't understand so i had to make a new question.

I believe the worst part of this issue is that feel that i understand far less then before i started this, ask me to write a simple (code simple with lots of if else) game, sure i will do that, ask me to make a website, yeah sure, but testing that stuff is fucking horrible... I never had any idea that unittests were such a hassle before now, and i am really put off by them. I do have a unittest that works, and the guy who wrote it shrugged and said "meh, it just works. I have no idea how" The expert on coding in class kept telling me that my original code was impossible to test, and insisted that this code is really easy to test but basically haven't answered me properly for two weeks now on how to actually write the test.

I am probably just retarded for not seeing it :( EDIT: to add i am using 2.7 python

Unit Testing - Setting Model Property Values

I'm currently in the process of writing a unit test, which is failing... It states: failed. Expected:<0>. Actual:<16>. I understand that this occurs because the RateManagement model is not getting set properly, but unsure how to set this data in my test.

Question: How can I populate the RateManagement model so that I can test the values correctly?

Failing Test

[TestMethod]
public void BabysitterBusiness_StartTimeBedTimeAndEndTimeAreRecorded_ReturnsCorrectAmountDue()
{
    // Arrange
    var data = new RateManagement
    {
        TotalBedtimeHours = TimeSpan.FromHours(3),
        TotalHoursBeforeBedtime = TimeSpan.FromHours(2),
        TotalOvertimeHours = TimeSpan.FromHours(4)
    };

    // Act
    var result = _business.CalculatePaymentDue();

    // Assert
    Assert.AreEqual(result, 16M);
}

RateManagement Class

public class RateManagement 
    {
        public TimeSpan TotalBedtimeHours { get; set; }
        public TimeSpan TotalOvertimeHours { get; set; }
        public TimeSpan TotalHoursBeforeBedtime { get; set; }
    }

Business Class

using System;
using System.Globalization;
using BabysitterKata.Models;

namespace BabysitterKata.Business
{
    public class BabysitterBusiness
    {
        private readonly TimeManagement _timeManagement;
        private readonly RateManagement _rateManagement;
        private readonly HourlyRate _hourlyRate = new HourlyRate
        {
            StartingRate = 12M,
            BedtimeRate = 8M,
            OvertimeRate = 16M
        };

        public BabysitterBusiness(TimeManagement timeManagement, RateManagement rateManagement)
        {
            _timeManagement = timeManagement;
            _rateManagement = rateManagement;
        }

        public decimal CalculatePaymentDue()
        {
            // calculate amount due for total hours
            var beforeBedtimeAmountDue = _hourlyRate.StartingRate * _rateManagement.TotalHoursBeforeBedtime.Hours;
            var duringBedtimeAmountDue = _hourlyRate.BedtimeRate * _rateManagement.TotalBedtimeHours.Hours;
            var afterHoursAmountDue = _hourlyRate.OvertimeRate * _rateManagement.TotalOvertimeHours.Hours;

            // rounding up if not at start of hour
            if (_rateManagement.TotalHoursBeforeBedtime.Minutes != 00)
            {
                beforeBedtimeAmountDue += _hourlyRate.StartingRate;
            }

            if (_rateManagement.TotalBedtimeHours.Minutes != 00)
            {
                duringBedtimeAmountDue += _hourlyRate.BedtimeRate;
            }

            if (_rateManagement.TotalOvertimeHours.Minutes != 00)
            {
                afterHoursAmountDue += _hourlyRate.OvertimeRate;
            }

            return beforeBedtimeAmountDue + duringBedtimeAmountDue + afterHoursAmountDue;
        }
    }
}

Include process in unit test and code coverage?

I'm trying to find a code coverage solution for an installation of Visual Studio 2015 to be executed from a build server (Visual Studio Team Services / TFS).

Inside the solution of my project I have unit tests that are collecting code coverage information, but I'm not getting complete coverage from traditional unit tests alone. I've created a unit test that starts a process and gets screenshots of a 3D scene and diffs them versus ones that are human verified.

I can get the process to run off of the same assemblies as the unit test, but I'm not sure how to get the code coverage result from the process and then merge it with the active unit test run.

Am I approaching this the wrong way or is there a way to get the coverage results from the process run and merge them with the rest of the unit test code coverage results before TFS publishes the test results?

Running Unit Test on ASP.Net MVC5 with DbContext

I currently using Unit Testing on my projects but it seems I have trouble on getting the data on my site DBContext, I assume that I need to run the web project then run the test but I dont think Visual Studio permits that.

So I tried opening 2 instances of Visual Studio but it still did not work.

This is my code:

    private ApplicationDbContext db = new ApplicationDbContext();
    [TestMethod]
    public void IsDbNull()
    { 
        var dblist = db.StudentInformation.ToList(); 
        Assert.IsNotNull(dblist);
    }

A simple assert to check if the project can read my database, I tried debuging and dblist doesn't have any items on it.

I saw some codes that uses fake database by putting it as CSV but as much I dont want to go that method since I want to test the real data itself.

I also saw "Run Tests" on GitHub but it only supports VS 2012

How to test a controller method that uses a custom parser in play 2.5?

My controller method:

def postCategory = Action(parse.tolerantText) { request =>
    Ok("")
  }

and this is my test:

val result = categoryController.postCategory.apply(FakeRequest())
      status(result) mustEqual OK //error this line

I have this error:

Error:(63, 14) type mismatch; found : play.api.libs.streams.Accumulator[akka.util.ByteString,play.api.mvc.Result] required: scala.concurrent.Future[play.api.mvc.Result] status(result) mustEqual OK ^

It seem that using a custom parser parse.* makes it returns Accumulator rather than Future[Result]

I'm using play 2.5-RC2

A tale of two mocks...same object type, but different subsequent actions - how to associate correct object with correct expectations?

When unit testing with mock objects and using PowerMock or PowerMokito to intercept instantiation of objects within the class under test, how does one handle the case where multiple instantiations of the same object occur, but each created instance must be a different mock object because they end up doing different things?

For example consider this class under test, which instantiates two objects of the same type. The constructor has no arguments, so I can't use argument matchers to distinguish the two objects when they are created:

public class classUnderTest {

    someTypeOfObject A;
    someTypeOfObject B;

    public void someMethod() {
        Object A = new someTypeOfObject();
        Object B = new someTypeOfObject();

        //Object A does something
        A.doSomething();

        //Object B does something *different*
        B.doSoemthingDifferent();

    }
}

I can then naively write a test for this, which returns a mock for Object A in the first instantiation, then a mock for Object B in the second.

public class testClass extends EasyMockSupport {
    public void testTheClassUnderTest() throws Exception {
        /* Create mocks for Object A and b */
        mockOfObjectA = mock(someTypeOfObject);
        mockOfObjectB = mock(someTypeOfObject);

        /* <----- Setup Mock expectations -------> */
        // Intercept Instantiation of object A, and return mock
        PowerMock.expectNew(someTypeOfObject.class)
                .andReturn(mockOfObjectA)
                .once();
        // Intercept Instantiation of object B, and return mock
        PowerMock.expectNew(someTypeOfObject.class)
                .andReturn(mockOfObjectB)
                .once();

        //<--Object A does something, returns itself for call chaining
        PowerMock.expect(mockOfObjectA.doSomething)
                .andReturn(mockOfObjectA);

        //<--Object B does something, returns itself for call chaining
        PowerMock.expect(mockOfObjectB.doSomethingDifferent)
                .andReturn(mockOfObjectB);
        /* <----- Done setting up mock expectations ------------> */

        //...more code to exercise object under test and verify expecations
    }
}

HOWEVER, there is nothing about the code that implies that Object A must be created before Object B. Object A and B are identical when they are created, and the arguments to the constructor are the same, so I don't see a way to tell PowerMock how to distinguish them so it can return the mocks for Object A or B when appropriate. So while the above test will work with the above code, the test will break if the code is ever refactored like this:

public class classUnderTest {

    someTypeOfObject A;
    someTypeOfObject B;

    public void someMethod() {
        Object B = new someTypeOfObject(); //<--Object B created first
        Object A = new someTypeOfObject();


        //Object A does something
        A.doSomething();

        //Object B does something *different*
        B.doSoemthingDifferent();

    }
}

How can I tell PowerMock how to distinguish object A from Object B during instantiation? Or is there some way to swap the expectations recorded between two objects so that I can handle the two cases (i.e. if verifyAll() fails, swap expectations between mockOfObjectA and mockOfObjectB and check again before failing the test).

Note that I don't own the class being instantiated, so answers involving modifications to the class under test cannot be used. Also, I'd really prefer to have an answer which doesn't drive anything about the implementation of the code under test.

Kotlin: Make an internal function visible for unit tests

In case the tests are in a different module than the production code (which is common), what's the best way to make internal functions visible for tests?

In Java, I would have the production code and the test in the same package and make the methods-to-be-tested package-private (plus, add a @VisibleForTest annotation if the only reason for having it package-private rather than private is the test). Unfortunately, Kotlin doesn't have the concept of package-private.

Java J-unit tests

I am testing a class that was implemented from an interface. In my test class, I have created objects (Humains) that have a name and bank account value.

One of my methods to test takes an arrayList and compares with another list and if the person already exists, the amount will be added.

Code is something like that: TEST CLASS

HumainImpl<Humain> humain = new HumainImpl<Humain>();
private Humain h1 = new Humain("AAA" , 2200);
private Humain h2 = new Humain("DDD" , 500);

@Test
public void testAddAmount(){
List<Humain> testing = new ArrayList<Humain>();
testing.add(h1);
testing.add(h2);

humain.placeList(testing);
}

the placeList(testing) method is in the HumainImpl class which calls another method in the Humain class that does the addition. In the HumainImpl class there is also a list called implList. Once this method placeList is called, the numbers for h1 and h2 in the test class are changing. What I want, is that only the number for the implList to change.

Is it something normal that when adding up numbers or making changes while passing the h1 and h2 as parameter they will get effected ?

I have tried too many ways and I don't get it. I tried going through the list passed as a parameter copy the element in that list into another attribut and do the addition but it didn't help.

This works fine when I test another similar method that takes an element as a attribut, place(h1).

How to access private members in unit tests?

While developing unit tests, accessing private members to check the internal state of the class can be necessary. Sometimes getter and setter functions are not available, sometimes they are not public.

First method to handle that, writing a preprocessor define writes publis instead of private and protected.

#define protected public
#define private public

Second method is making the test classes friends of the classes.

class test_foo {
};

class foo {
private:
  int mem;

  friend class test_foo;
};

A third method is creating public interface for test.

class foo {

#if defined FOO_UNIT_TEST
public:
  int get_mem() const;
#endif

private:
  int mem;
};

Is there any other method except these methods? Every method has pros and cons. Which one can be thought as best practice?

Thanks.

Why is element scope null in directive unit test?

I have created a custom directive that has a watch for a couple of isolated scope properties, here is the relevant code:

 scope.$watchGroup(['repairer', 'initial'], function () {

           scope.Repairer = null;
...

           scriptingService.getScript(request).then(function (scripts) {
                            scope.scripts = scripts;
                        });

I wrote a couple of test but none of them work,this is one of them:

it('should  Repairer be 2', function() {

    scope.$apply(function() {
      scope.initial = 2;
    });

    expect(element.isolateScope().Repairer).toEqual(2);

  });

But I am getting an error:

TypeError: Cannot read property 'Repairer' of undefined

How can I make the tests work? Looks like the directive is somehow not running in the test.

Here is a plunkerref:http://ift.tt/21sciDv

How do I mock a text output from reading a file in C# using the Moq Framework on Monodevelop

I've been banging my head on this all weekend. Basically I am doing a code kata for Game of Life and it involves reading in a text file. I take in that text file which contains two dimensional representation of the grid and stores all the points in a List of List's. I am trying to mock the text input obtained from the file to just be '\n' a new line so I can write unit tests checking that there is a new List being created within the List of Lists. I have created a file wrapper to handle the reading of the text file and that is what I am trying to mock. The code complies fine but the test fails with the error message "System.ArgumentException : The specified path is not of a legal form". It seems to still be expecting a file path but the mocking should change this behaviour right? Any help would be appreciated.


using System.Collections.Generic;

namespace GameOfLife
{
    public class InitializeGrid
    {

        public InitializeGrid ()
        {
        }

        public List<List<char>> CreateCharMatrix (string filePathName)
        {
            // Reads in the text file containing the grid data
            FileWrapper fileWrapper = new FileWrapper ();
            string inputGridTextFile = fileWrapper.ReadTextFromFile (filePathName);

            // Creates character matrix and initialises the first sub List
            List<List<char>> charMatrix = new List<List<char>> ();
            charMatrix.Add(new List<char>());

            int rowIndex = 0;
            int colIndex = 0;

            foreach (char cell in inputGridTextFile) {
                if (cell == '\n') {
                    charMatrix.Add (new List<char> ());
                    rowIndex++;
                    colIndex = 0;
                } else {
                    charMatrix [rowIndex] [colIndex] = cell;
                    colIndex++;
                }
            }

            return charMatrix;
        }

    }
}


using NUnit.Framework;
using System;
using System.Collections.Generic;
using Moq;

namespace GameOfLife

    [TestFixture()]
    public class InitializeGridTest
    {
        [Test()]
        public void CreateCharMatrix_EnsuresThatWhenEndOfLineReachedNewSubListCreated()
        {
            //Arrange

            InitializeGrid initializeGrid = new InitializeGrid ();
            List<List<char>> charMatrix;
            string filePathName = " ";

            Mock<IFileWrapper> mockFileWrapper = new Mock<IFileWrapper> ();
            mockFileWrapper.Setup<string> (m => m.ReadTextFromFile (It.IsAny<string>())).Returns ("\n");
            mockFileWrapper.Setup (m => m.ReadTextFromFile (It.IsAny<string>())).Returns ("\n");

            //Act
            charMatrix = initializeGrid.CreateCharMatrix (filePathName);
            int countProvingAnAdditionalListHasBeenAdded = charMatrix.Count;

            //Assert
            Assert.AreEqual (2, countProvingAnAdditionalListHasBeenAdded);
        }
    }


using System;
using System.IO;

namespace GameOfLife
{
    public class FileWrapper : IFileWrapper
    {
        public string ReadTextFromFile(string path)
        {
            return File.ReadAllText (path);
        }
    }
}


using System;

namespace GameOfLife
{
    public interface IFileWrapper
    {
        string ReadTextFromFile(string filePathName);
    }
} 

How to unit test database functions? (Doctrine2)

I may dont understand the concept of testing. Here is a function:

$qb->select('u')
   ->from('User', 'u')
   ->where('u.id = ?1')
   ->orderBy('u.name', 'ASC');

it is then "very" easy to write a mock, replace, expect the parameters, expect something result, etc. This is also detached from the database (no need real database then).

But what if I miss the ordering? I can still write a good test for it, without making sure it actually works. Another example:

function add($a, $b)
{
    return $a-$b;
}

our imaginary test:

function testAdd()
{
    $a = 1;
    $b = 4;

    $mock = $this->getMock(test);
    $mock->expects($a)->once()->with(1);
    $mock->expects($b)->once()->with(4);

    $this->assertEquals (-4324,534, testAdd($a, $b);
}

this (fictional) test is similar to database test above. Lets take some parameters, expect that they run once, and produces a fake value. But actually, I still dont know it my "Add" method works well.

samedi 27 février 2016

Nodejs - Mocha, Chai multiple async testing

Complete NodeJS testing noob here. Trying to individually test functions that are called through my API (meaning, rather than make an http request to a specific endpoint, which usually invokes several functions, which in turn make requests to different third party APIs, I want to test the functions themselves separately). The way they're called is I've built a class for each data source (data source = third party API), each class contains the same functions with the same exact signatures - getData and convertData, and return a callback with the results.

I've also created a module that creates many user mocks, since each user context returns different data (meaning, a user object is fed into getData, which uses certain user properties in order to determine what data should be returned).

The way I wanted to test this was to create numerous mocks, then run the functions for each. This is what I've got so far:

// Data sources to iterate over. Each is a class instance acquired through "require".
var dataSources = [
    source1,
    source2,
    source3,
    source4
];

describe('getData', function() {       
    this.timeout(10000);
    describe('per data source,', function() {
        context('standard call', function() {

            // Associative array to hold the data returned, a key for each data source.
            var finalResults = {};

            // Iterate over all data sources
            _.forEach(dataSources, function(dataSource) {

                // Generate user mocks
                var users = userMocks(10);

                // Iterate over all users. 
                _.forEach(users, function (user) {

                    // Call each data source with each of the users.
                    // Numbers of calls to make - (users * data-sources), so in this case - 10*4.
                    dataSource.getData(user, function (err, data) {
                        if (err) return done(err);

                        // Convert the data returned to my format
                        dataSource.convertData(data, function (err, processedData) {
                            if (err) return done(err);

                            // Populate finalResults with converted data from each source
                            if (finalResults[dataSource.sourceName]) {
                                finalResults[dataSource.sourceName] = finalResults[dataSource.sourceName].concat(processedData);
                            } else {
                                finalResults[dataSource.sourceName] = processedData;
                            }
                        });
                    });
                });
            });

            it('should return something', function(done) {
                _.forEach(finalResults.keys, function(key) {
                    expect(finalResults[key]).to.not.be.empty;
                    expect(finalResults[key].length).to.be.greaterThan(0);
                });
                setTimeout(function() {
                    done();
                }, 10000);
            })
        });
     });
});

});`

This works (or at least the test passes when the query is valid, which is what I wanted), but it's cumbersome and (so very) far from elegant or effective, specifically the usage of timeout rather than using promises, async of some sort, or maybe a different alternative I'm not yet familiar with.

Since most of the resources I found (http://ift.tt/21rLR0M, http://ift.tt/1RwFv87, http://ift.tt/21rLS4L, just to name a few) discuss direct API testing rather than specific async functions, I would love to get some input/best practices tips from more experienced Noders.