lundi 30 novembre 2015

Best way for unit testing in meteor app

I am working an meteor app, In which i want to perform unit testing for meteor app. I refereed about sanjo:jasmine and sanjo:jasmine testing package . I want to know which one is best in above both package or is any other way for unit testing of meteor app.

AngularJS - Mocking service functions. Undefined from Jasmine test

I'm having problems. I am using AngularJS v1.4.8 with Angular-Mocks and lodash. I have created a bare-bones simple AngularJS app that simply takes an object and adds onto it.

I would like to know how to mock an AngularJS service and its (instantiated) functions.

Here is my app/main/main.js controller:

'use strict';

angular.module('main', [
    'testapp.models.main'
])
    .config(function ($stateProvider) {
        $stateProvider
            .state('testapp.main', {
                url: '/',
                views: {
                    'mainview@': {
                        controller: 'MainCtrl as mainCtrl',
                        templateUrl: 'app/main/main.template.html'
                    }
                }
            });
    })
    .controller('MainCtrl', function MainCtrl($scope, MainModel){
        this.addItem = MainModel.addItem;
        this.listItems = MainModel.listItems();
    });

and here is its model of app/models/main-model.js:

angular.module('testapp.models.main', [])
    .service('MainModel', function () {

        var items  = [
            { 'id': 0, 'label': 'Item No. 1'},
            { 'id': 1, 'label': 'Item No. 2'},
            { 'id': 2, 'label': 'Item No. 3'},
            { 'id': 3, 'label': 'Item No. 4'}
        ];

        this.listItems = function() {
            return items;
        };

        this.addItem = function(label) {
            var newID = (Object.keys(items).length);
            var theLabel = label ? label :  _.random(10000, 1000000);
            items[newID] = {'id': newID, 'label': 'Item No. ' + theLabel };
        }

    });

and here is my karma.conf.js:

module.exports = function(config) {
    config.set({
        basePath: '../',
        frameworks: ['jasmine'],
        files: [
            // Vendor Files
            'bower_components/angular/angular.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'bower_components/angular-ui-router/release/angular-ui-router.js',
            'bower_components/lodash/lodash.min.js',
            'bower_components/sinon-1.17.2/index.js',

            // App-Specific Files
            'app/index.js',
            'app/models/*.js',
            'app/main/*.js',

            // Test-Specific Files
            'tests/mock/**/*.js'
        ],
        exclude: [],
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['PhantomJS'],
        singleRun: true,
        concurrency: Infinity
    })
};

and last not but not least, my mock file tests/mock/controllers/MainMock.js: (where I'm having the problem)

describe('Main Mock Unit Tests', function() {
    'use strict';

    beforeEach(module('ui.router'));
    beforeEach(module('main'));

    var MainCtrl,
        scope;

    var mocklistResource;

    beforeEach(function() {
        mocklistResource = sinon.stub({listItems: function() {}});

        module(function($provide) {
            $provide.value('main', mocklistResource);
        })
    });

    beforeEach(inject(function ($rootScope, $controller, $state) {
        scope = $rootScope.$new();

        MainCtrl = $controller('MainCtrl', {
            $scope: scope,
            $state: $state
        });
        scope.$digest();

    }));

    it('Items object to be 4 (default length)', function () {
        expect(Object.keys(MainCtrl.listItems).length).toBe(4);
    }); // passes


    it('should equal the mock list item object', inject(function() {
        expect(mocklistResource.listItems[0]).toEqual('Item No. 1');
    }))
});

The error comes from the MainMock.js file on the second (and last) it function, gives me:

Expected undefined to equal 'Item No. 1'.

I am trying to get the mocked function of getting the list objects and should return as Item No. 1 successfully but I am getting undefined.

What am I doing wrong? How do I mock this service test? (If there's a better way to do mock tests without sinon, then please let me know.)

Robolectric with third party libraries

My project include several third party libraries like crashlytics, facebook sdk and so on. Some of them require to do initialization on activity startup, however under gradle unit test it will fails, how to avoid this? mocking or use a runtime flag to bypass it?

sdn 4.0 wired behaviour in unit test

This is bit strange for me. I have a company repository

@Repository
public interface CompanyRepository extends GraphRepository<Company> {

    Company findByName(String name);

    @Query("MATCH (n:Company) WHERE lower(n.name) CONTAINS lower({0}) RETURN n")
    List<Company> findByPartialName(String name);

then I have a unit test class to test those two methods

public class CompanyRepositoryTest extends Neo4JTestConfig {

@Autowired
private CompanyRepository companyRepository;

@Before
public void setUp() throws Exception {

    Company company = new Company();
    company.setName("Westpac");
    company.setUrl("www.westpac.com.au");

    companyRepository.save(company);

    Company company2 = new Company();
    company2.setName("test Hl");
    company2.setUrl("www.test.com.au");

    companyRepository.save(company2);
}

@After
public void tearDown() throws Exception {
    companyRepository.deleteAll();
}

@Test
public void testFindByName() throws Exception {

    Company company = companyRepository.findByName("Westpac");
    assertEquals(company.getUrl(), "www.westpac.com.au");
}

@Test
public void testFindByPartialName() throws Exception {

    List<Company> companies = companyRepository.findByPartialName("St");
    assertEquals(2, companies.size());

    List<Company> companies2 = companyRepository.findByPartialName("west");
    assertEquals(1, companies2.size());
}
}

those are looks all good? yep, I think so. I can run each @Test method with out any problems.

However, when I run the on the class level, whatever the 2nd test method always failed.

I looked into the database, the 1st time run @Before, it is all good, two Company are saved into neo4j with the name and url properties. But for the 2nd time run of @Before, all the Company node in neo4j does not have any properties. This is causing the 2nd @Test failed.

I am using

<spring.data.neo4j.version>4.0.0.RELEASE</spring.data.neo4j.version>

and

<neo4j.ogm.version>1.1.2</neo4j.ogm.version>

any idea why?

Android PointF constructor not working in JUnit test

I have just stumbled on this while trying to write a JUnit test. Admittedly this is my first unit test in JUnit, but I do find the behaviour very puzzling.

package com.example.dom.pointfbugrepro;

import android.graphics.PointF;
import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleUnitTest {
    @Test
    public void pointf_isCorrect() throws Exception {
        PointF foo = new PointF(5, 0);
        assertEquals(5, foo.x, 0.0001f);
    }
}

Running this test in a brand new Android Project results in an assertion failure:

java.lang.AssertionError: 
Expected :5.0
Actual   :0.0

One thing I found out while investigating this problem is that assigning to the PointF instance's x field directly does work.

So what is the problem here? Why doesn't the constructor set the fields properly? and how should I be testing classes which use the PointF Android class?

Can someone tell me why there is difference between System.out.println() and System.out.print("\n")?

Recently I am doing the project of my software testing course. Today, when I am doing the Junit test to one of the functions in the test code, I come across this question. My test code is about the binary search tree, this unit test is testing its printTree function. When I create a new tree and use the function to print it out, I want to convert it to String so that I can use assertEquals to compare the output with the desired value.

public class TestofPrintTree {

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
}

@After
public void cleanUpStreams() {
    System.setOut(null);
}

@Test
public void testPrintTree() {

    BinarySearchTree t = new BinarySearchTree( );
    t.printTree( );
    assertEquals("Empty tree\n", outContent.toString());
}

and in the printTree()

    public void printTree( )
{
    if( isEmpty( ) )
        System.out.println( "Empty tree" );
    else
        printTree( root );
}

The problem is that the failure trace told me that the comparison failed. However, when I click to open the failure trace, the desired value and real value, they are exactly the same. The only difference is hereenter image description here

Can someone tell me what is the difference between System.out.println() and System.out.print("\n") in the question I come across?

Controller test for update, show and destroy does't work for referenced class

I have the "users" and the "empresas", i used the scaffold command to generate the initial CRUD for "empresas" and after that i put the users id into the empresas and all the model need to, so what i want is to just the users that are the owner of the empresa can have acess to the "show", "update" and "destroy", i have a correct_user function and before action to apply that on the actions, everything works fine, unless the tests, i just apply the login into the original scaffold tests.

Empresas Controller

class EmpresasController < ApplicationController
  before_action :set_empresa, only: [:show, :edit, :update, :destroy]
  before_action :logged_in_user, only: [:update, :show, :index, :create, :destroy]
  before_action :correct_user,   only: [:show, :update, :destroy]

  # GET /empresas
  # GET /empresas.json
  def index
    @empresas = current_user.empresas.all
  end

  # GET /empresas/1
  # GET /empresas/1.json
  def show
  end

  # GET /empresas/new
  def new
    @empresa = Empresa.new
  end

  # GET /empresas/1/edit
  def edit
  end

  # POST /empresas
  # POST /empresas.json
  def create
    @empresa = current_user.empresas.build(empresa_params)
    respond_to do |format|
      if @empresa.save
        format.html { redirect_to @empresa, notice: 'Empresa criada com sucesso.' }
        format.json { render :show, status: :created, location: @empresa }
      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /empresas/1
  # PATCH/PUT /empresas/1.json
  def update
    respond_to do |format|
      if @empresa.update(empresa_params)
        format.html { redirect_to @empresa, notice: 'Empresa alterada com sucesso.' }
        format.json { render :show, status: :ok, location: @empresa }
      else
        format.html { render :edit }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /empresas/1
  # DELETE /empresas/1.json
  def destroy
    @empresa.destroy
    respond_to do |format|
      format.html { redirect_to empresas_url, notice: 'Empresa removida com sucesso.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_empresa
      @empresa = current_user.empresas.find_by(id: params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def empresa_params
      params.require(:empresa).permit(:nome_fantasia, :email, :razao_soc, :cnpj)
    end

    def correct_user
      @empresa = current_user.empresas.find_by(id: params[:id])
      redirect_to empresas_url if @empresa.nil?
    end

end

Empresas_controller test

require 'test_helper'

class EmpresasControllerTest < ActionController::TestCase
  setup do
    @user = users(:carlos)
    @empresa = empresas(:one)
    @empresa.user_id = @user.id
  end

  test "should get index" do
    log_in_as(users(:carlos))
    get :index
    assert_response :success
    assert_not_nil assigns(:empresas)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count') do
      post :create, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    end

    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should show empresa" do
    log_in_as(users(:carlos))
    get :show, id: @empresa
    assert_response :success
  end

  test "should get edit" do
    log_in_as(users(:carlos))
    get :edit, id: @empresa
    assert_response :success
  end

  test "should update empresa" do
    log_in_as(users(:carlos))
    patch :update, id: @empresa, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should destroy empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count', -1) do
      delete :destroy, id: @empresa
    end

    assert_redirected_to empresas_path
  end


end

The erros msgs

FAIL["test_should_destroy_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_destroy_empresa#EmpresasControllerTest (1447412845.23s)
        "Empresa.count" didn't change by -1.
        Expected: 2
          Actual: 3
        test/controllers/empresas_controller_test.rb:51:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_get_edit", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_get_edit#EmpresasControllerTest (1447412845.33s)
ActionView::Template::Error:         ActionView::Template::Error: First argument in form cannot contain nil or be empty
            app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
            app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
            test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'
        app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
        app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
        test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'

 FAIL["test_should_show_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_show_empresa#EmpresasControllerTest (1447412845.35s)
        Expected response to be a <success>, but was <302>
        test/controllers/empresas_controller_test.rb:34:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_update_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_update_empresa#EmpresasControllerTest (1447412845.36s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"empresas", :id=>nil} missing required keys: [:id]
            test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'
        test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'

  61/61: [==================================================================================================================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.21698s
61 tests, 166 assertions, 2 failures, 2 errors, 0 skips

Everything are working, but i realy want to learn tests

Symfony web test case JSON

How can I run a webtestcase agains an API? The default guide regarding functional tests only give the following command:

$client = static::createClient();
$crawler = $client->request('GET', '/some-url');

The Crawler class is a DOM crawler. I checked the reference for the FrameworkBundle\Client class and I couldn't find a method that will allow me to make a request that returns raw Response. At least that way, I will be able to json_decode the output and do my tests.

What can I use to achieve this?

Mock WCF service for another instance

There are two solutions: Web and Server that communicate with wcf services. Another solution is Test where I'm writing UI tests. In this Test solution I have Host project where I have service references to Server solution. Then I just implement fake services from interfaces of referenced services. And depending on build configuration Web use link to fake host from config. So in this way I've separated Web testing from server side, and another benefit it's speed. In the test I need, for example, verify that method was called with appropriate parameters and return something back when I press the button. So in the implementation of the fake method I need to log all parameters and return some information that depends from these parameters. But I'm trying to find another way how to mock it, for example how it looks with Rhino mocks. And test can looks something like this.

Page.PressAddCustomerButton();  
mock.Expect(t => t.AddCustomer("Name", "Surname")).Return(response.Ok);

Could you please help me. Is it possible?

Unit testing static methods using moq issue

I am having trouble understanding why there is discrepancy between these two tests.

First, Test A:

Public Sub GetTypes_Success()
    _context = New Mock(Of IFraternalEntities)()
    _cacheProvider = New Mock(Of ICacheProvider)()

    Dim type1 = EntityCreator.Create(Of SomeType)()
    Dim type2 = EntityCreator.Create(Of SomeType)()
    Dim listOfTypes = New List(Of SomeType)({type1, type2})
    _context.Setup(Function(r) r.SomeTypes).Returns(QueryableMockSet(Of SomeType).Create(listOfTypes.AsQueryable()).Object)

    _repo = New TypeRepo(_context.Object, _cacheProvider.Object)
    Dim results = _repo.GetSomeTypes()

    Assert.AreEqual(listOfTypes.Count, results.Count, "Not all types returned")
End Sub

testing the method

Public Function GetSomeTypes() As IEnumerable(Of DTO.SomeType) Implements ITypeRepo.GetSomeTypes
    Dim results = Entities.SomeTypes.OrderBy(Function(x) x.SortOrder).AsEnumerable()
    Return results.Select(Function(x) New DTO.SomeType With {
            .TypeID = x.TypeID,
            .Name = x.Name,
            .Description = x.Description
    })
End Function

This test works perfectly. However, I have a dang near equal test here, Test B:

Public Sub GetSecondaryTypes_Success()
    _context = New Mock(Of IFraternalEntities)()
    _cacheProvider = New Mock(Of ICacheProvider)()

    Dim type1 = EntityCreator.Create(Of OtherType)()
    Dim type2 = EntityCreator.Create(Of OtherType)()
    Dim listOfOtherTypes = New List(Of OtherTypes)({type1, type2})
    _context.Setup(Function(r) r.OtherTypes).Returns(QueryableMockSet(Of OtherType).Create(listOfOtherTypes.AsQueryable()).Object)
    _repo = New TypeRepo(_context.Object, _cacheProvider.Object)
    Dim results = _repo.GetOtherTypes()
    Assert.AreEqual(listOfOtherTypes.Count, results.Count, "Not all types returned")
End Sub

Testing this method

Public Function GetOtherTypes() As IEnumerable(Of DTO.OtherType) Implements ITypeRepo.GetOtherTypes
    Dim results = Entities.OtherTypes.AsEnumerable()
    Return results.Select(Function(x) x.MapToDTO())
End Function

with the MapToDTO() looking like this:

<Extension>
    Function MapToDTO(entity As NaturalDisaster) As DTO.NaturalDisaster
        Dim dto = New DTO.NaturalDisaster With {
            .TypeID= entity.TypeID,
            ''lots of other properties here
        }
        Return dto
    End Function

I understand that the Select causes the error NotSupportedException: expression references a method that does not belong to the mocked object. I also understand that doing

_context.setup(function(r) r.OtherTypes.AsEnumerable()).Returns(''this stuff here)

does not work because at this point we are dealing with a linq query. Can someone give me some insight on to why the first method works but the second method does not?

In advance, I may have made an error when transcribing my code onto here, so if it is a syntax error I will correct it.

Thanks

How would I perform property-based testing on a card game's Deal function?

I am studying property-based testing and am curious how I would apply this type of testing to a BlackJack game's Deal function.

Here's a unit test (aka: Example-based test):

[<Test>]
let ``deal two cards`` () =
    let hand = 2
    let dealPlayer cardCount = 
        [for i in [1..cardCount] -> shuffleDeck.Pop] 
        |> Seq.toList

    (dealPlayer hand).Length |> should equal (2)

What would be an example of a property-based test?

  • Would I test that the two cards are within a range of 4 suits? (i.e. Spades, Diamonds, Hearts, Clubs) Wouldn't relying on a static type already ensure that for me?

  • Would I test that the two cards are within the range of numbers or faces? (i.e. 2..10;Jack;Queen;King;Ace) Again, wouldn't relying on a static type already ensure that for me?

Again, what should I consider when performing property-based tests for a blackjack game?

Shimmed method not used by test in Release mode

Within Visual Studio 2015 I have a test project to which I've added a fakes assembly.

In the unit test itself I create a shim for a static generic method that returns an instance to the generic type, such as:

using (ShimsContext.Create())
{
    ShimStaticClass.TheMethod<MyType>(() => instanceOfMyType);

    // ... code that uses StaticClass.TheMethod here ...
}

When the solution is built in debug mode the test runs fine and passes. However, when the solution is built in release mode the shimmed version of TheMethod does not get called, which is causing the test to fail.

I know that the shimmed method is not called because I've changed it to throw an exception by doing:

using (ShimsContext.Create())
{
    ShimForStaticClass.TheMethod<MyType>(() => 
    {
        throw new InvalidOperationException("Shim was called");
    });

    // ... code that uses StaticClass.TheMethod here ...
}

and this exception is not thrown.

I've turned on diagnostic logging and noisy verbosity for the fake but the build logs do not indicate any issues.

Running Web Component Tester Locally

Do I have to install Web Component Tester (wct) globally? E.g. npm install -g web-component-tester. Is there any way to install it as a local module? E.g. npm install web-component-tester. If so, how do I execute it?

Write test method for MVVM- Ninject DI - Entity Framework

I'm learning to write test method. But I still don't know how to created fake data for the test class.

Here's my code:

public interface IData
{
    Staff GetUser(string username, string password);
}
// Implement class , which get data from a DataContext
public class EFData: IData
{
    HotelDataContext dataContext;

    public Staff GetUser(string username, string password)
    {
        var staff = dataContext.Staffs.Where(s => s.Username == username && s.Password == password).FirstOrDefault();
        return staff;
    }
}

// My ViewModel which I want to test
public class StaffViewModel: INotifyPropertyChanged
{
    IData _data;

    // I use Ninject for Dependency Injection here
    public StaffViewModel(IData data)
    {
        _data = data;
    }

    // I want to test this method
    public bool Login(string username, string password)
    {
        var staff = _data.GetUser(username, password);
        return (null != staff);
    }
}

As I know, now I need to write some class like this , but I have no idea how to create the test data for this method.

[TestClass]
public class StaffVMTest
{
    [TestMethod]
    public void TestLogin()
    {
        ////
        //   wrong_test_username, pw ; success_test_username, pw   = ????
        ////

        var testResult1 = vm.Login(wrong_test_username, wrong_test_pw);
        var testResult2 = vm.Login(success_test_username, success_test_pw);

        Assert.AreEqual(false, testResult1);            
        Assert.AreEqual(true, testResult2);
    }
}

Salesforce Trigger Test Error

Hello!

I am working on unit tests for trigger within Salesforce and I keep encountering an error that I can't seem to solve so I am hoping someone with more experience can help me get back on track. I've hunted around on Google and messed with the structure of my code many times but I'm unable to find a solution.

Purpose:
I have been tasked with writing a trigger that will handle the logic required to maintain case rankings per developer. Each developer is assigned cases and those cases may or may not have a priority determined by the business. Each developer may only have 10 cases prioritized at any one time. Any other cases will just have a null value in the ranking field. If a case with a ranking is inserted, updated, or deleted then all the other cases assigned to that developer with a rank must automatically update accordingly. Any case with a rank higher than 10 will get nulled out.

Problem:
I have completed the trigger and trigger handler class now I am writing unit tests to cover all the unit tests. When I finished my first unit test method I got an error that referenced a workflow issue. I found and corrected the issue but after I finished my second unit test method I get the same error again. I can comment out either of the two methods and the other passes but whenever I run them together I get a pass on the first and a fail on the second with the same original error.

Error:
System.DmlException: Upsert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, A workflow or approval field update caused an error when saving this record. Contact your administrator to resolve it. Developer Assigned Email: invalid email address: false: []

Code:

Trigger Code -

/***************************************************************************************
* @author:      Michael *REDACTED*
* @email:        michael.*REDACTED*@*REDACTED*.com
* @date:         11/09/15
* @brief:         This is a trigger for the Case object that will modify the rank of the Cases
*                     assigned to the developer based on a priority set by the Administrator.
***************************************************************************************/
trigger CaseRankTrigger on Case (before insert, before update, before delete) {
    // trigger level variables
    private static Boolean firstRun = true;
    private RecordType ticketRecordType = [SELECT Id FROM RecordType WHERE SobjectType = 'Case' AND Name = 'Salesforce Service Ticket' LIMIT 1];
    private List<Case> newTrigger = trigger.new;
    private List<Case> currentTrigger = trigger.old;
    private List<Case> qualifiedNewCases = new List<Case>();
    private List<Case> qualifiedCurrentCases = new List<Case>();
     // makes sure that the trigger only runs once
    if (firstRun) {
        firstRun = false;
        // populate trigger Case lists
        qualifyCases();
        if (qualifiedNewCases.size() == 1 || qualifiedCurrentCases.size() == 1) {
            // the CaseRankTriggerHandler constructor method takes (List<Case>, List<Case>, String)
            if (trigger.isInsert) CaseRankTriggerHandler handler = new CaseRankTriggerHandler(qualifiedNewCases, qualifiedCurrentCases, 'Insert'); // if a new Case is being inserted into the database
            if (trigger.isUpdate) CaseRankTriggerHandler handler = new CaseRankTriggerHandler(qualifiedNewCases, qualifiedCurrentCases, 'Update'); // if an existing Case is being updated
            if (trigger.isDelete) CaseRankTriggerHandler handler = new CaseRankTriggerHandler(qualifiedNewCases, qualifiedCurrentCases, 'Delete'); // if an existing Case is deleted from the database
        }
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/24/15
    * @brief:       The qualifyCases method populates a list of Cases for each trigger
    *                   that are of the Salesforce Service Ticket record type only.
    * @return:     Void
    ***************************************************************************************/
    public void qualifyCases() {
        if (newTrigger != null ) {
            for (Case c : newTrigger) {
                if (c.recordTypeId == ticketRecordType.Id) {
                    qualifiedNewCases.add(c);
                }
            }
        }
        if (currentTrigger != null) {
            for (Case c : currentTrigger) {
                if (c.recordTypeId == ticketRecordType.Id) {
                    qualifiedCurrentCases.add(c);
                }
            }
        }
    }
}

Trigger Handler Code -

/***************************************************************************************
* @author:      Michael *REDACTED*
* @email:        michael.*REDACTED*@*REDACTED*.com
* @date:         11/09/15
* @brief:         This is a Case object trigger handler class that provides logic to the CaseRankTrigger for manipulating
*                     the ranks of all Cases assigned to a developer based on a priority that is set by an Administrator.
***************************************************************************************/
public with sharing class CaseRankTriggerHandler {
    // class level variables
    private static Boolean firstRun = true;
    private static Boolean modify = false;
    private static Integer MAX = 10;
    private static Integer MIN = 1;
    private List<Case> newTrigger {get; set;}
    private List<Case> currentTrigger {get; set;}
    private List<Case> cases {get; set;}
    private List<Case> newList {get; set;}
    private List<Case> currentList {get; set;}
    private String developer {get; set;}
    private Decimal newRank {get; set;}
    private Decimal currentRank {get; set;}
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       Class constructor method.
    * @return:     Void
    ***************************************************************************************/
    public CaseRankTriggerHandler(List<Case> newT, List<Case> oldT, String type) {
        if (firstRun) { // makes sure that the trigger only runs once
            firstRun = false;
            InitializeTrigger(newT, oldT, type); // initializes the trigger
            if (developer != null) { // skips trigger if DML is performed on a Case with no developer assigned
                ModificationCheck(type); // determines if Cases need to be modified
                if (modify) ModificationLogic(type); // modifies Cases if needed
            }
        }
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       The InitializeTrigger method initializes the handler class based on the type of trigger fired.
    * @return:     Void
    ***************************************************************************************/
    private void InitializeTrigger(List<Case> newT, List<Case> oldT, String type) {
        if (type == 'Insert') {
            this.newTrigger = newT;
            this.developer = newTrigger[0].Resource_Assigned__c;
            this.newRank = newTrigger[0].Case_Rank__c;
            this.newList = [SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Resource_Assigned__c = :developer AND Case_Rank__c != null AND Case_Rank__c = :newRank ORDER BY Case_Rank__c];
        } else if (type == 'Update') {
            this.newTrigger = newT;
            this.currentTrigger = oldT;
            this.developer = newTrigger[0].Resource_Assigned__c;
            this.newRank = newTrigger[0].Case_Rank__c;
            this.currentRank = currentTrigger[0].Case_Rank__c;
            this.newList = [SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Resource_Assigned__c = :developer AND Case_Rank__c != null AND Case_Rank__c = :newRank ORDER BY Case_Rank__c];
            this.currentList = [SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Resource_Assigned__c = :developer AND Case_Rank__c != null AND Case_Rank__c = :currentRank ORDER BY Case_Rank__c];
        } else if (type == 'Delete') {
            this.currentTrigger = oldT;
            this.developer = currentTrigger[0].Resource_Assigned__c;
            this.currentRank = currentTrigger[0].Case_Rank__c;
        }
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       The ModificationCheck method ensures various conditions are met, depending on the type
    *                   of trigger that was fired, before modifying the ranks of the Cases assigned to the developer.
    * @return:     Void
    ***************************************************************************************/
    private void ModificationCheck(String type) {
        if (type == 'Insert') {
            // the Case being inserted has a new rank not equal to null and if the assigned developer already has a Case with the
            // same rank as the new rank, we will proceed to modification, if not the record will be inserted without modification.
            if (newRank != null && !newList.isEmpty()) {
                modify = true;
            }
        } else if (type == 'Update') {
            // if the Case being updated has ranks with different values in both triggers we will proceed to the next check, if not the record is updated without modification.
            if (newRank != currentRank) {
                // if the Case being updated has a (new rank equal to null and a current rank not equal to 10) or
                // if the Case being updated has a new rank not equal to null, we will proceed to the next check,
                // if not the record is updated without modification.
                if ((newRank == null && currentRank != 10) || newRank != null) {
                    // if the assigned developer on the Case being updated already has a Case with the same rank as the new or current rank, we will proceed to modification,
                    // if not the record is updated without modification.
                    if (!newList.isEmpty() || !currentList.isEmpty()) {
                        modify = true;
                    }
                }
            }
        } else if (type == 'Delete') {
            // if the Case being deleted has current rank not equal to null, we will proceed to modification, if not the record is deleted without modification.
            if (currentRank != null) {
                modify = true;
            }
        }
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       If a Case rank needs to be updated the ModificationLogic method calls the appropriate
    *                   computation method based on trigger type and the values of newRank and currentRank.
    * @return:     Void
    ***************************************************************************************/
    private void ModificationLogic(String type) {
        if (type == 'Insert') {
            for (Case c : newTrigger) {
                // calls the IncreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank greater than or equal to the new rank.
                IncreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :newTrigger AND Resource_Assigned__c = :developer AND Case_Rank__c >= :newRank ORDER BY Case_Rank__c]);
            }
        } else if (type == 'Update') {
            for (Case c : newTrigger) {
                if (currentRank == null) {
                    // if the current rank is null - calls the IncreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank greater than or equal to the new rank.
                    IncreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :newTrigger AND Resource_Assigned__c = :developer AND Case_Rank__c >= :newRank ORDER BY Case_Rank__c]);
                } else if (newRank == null) {
                    // if the new rank is null - calls the DecreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank greater than the current rank.
                    DecreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :newTrigger AND Resource_Assigned__c = :developer AND Case_Rank__c > :currentRank ORDER BY Case_Rank__c]);
                } else if (newRank > currentRank) {
                    // if the new rank is greater than the current rank - calls the DecreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank less than or equal to the new rank and greater than to the current rank.
                    DecreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :newTrigger AND Resource_Assigned__c = :developer AND (Case_Rank__c <= :newRank AND Case_Rank__c > :currentRank) ORDER BY Case_Rank__c]);
                } else if (newRank < currentRank) {
                    // if the new rank is less than the current rank - calls the IncreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank a.
                    IncreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :newTrigger AND Resource_Assigned__c = :developer AND (Case_Rank__c >= :newRank AND Case_Rank__c < :currentRank) ORDER BY Case_Rank__c]);
                }
            }
        } else if (type == 'Delete') {
            for (Case c : currentTrigger) {
                // calls the DecreaseCaseRank method and passes it a list of Cases that are assigned to the developer that have a rank greater than the current rank.
                DecreaseCaseRank([SELECT Subject, CaseNumber, Case_Rank__c FROM Case WHERE Id NOT IN :currentTrigger AND Resource_Assigned__c = :developer AND Case_Rank__c > :currentRank ORDER BY Case_Rank__c]);
            }
        }
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       The DecreaseCaseRank method provides the logic required to properly
    *                   decrease or null out the ranks of the Cases assigned the the developer.
    * @return:     Void
    ***************************************************************************************/
    private void DecreaseCaseRank(List<Case> cases) {
        // if the list of Cases passed in by the ModificationLogic method isn't empty then it will iterate through the
        // list and decrease their ranks by 1 or null out the rank if it is not within the acceptable limits (1-10).
        if (!cases.isEmpty()) {
            for (Case c : cases) {
                if (c.Case_Rank__c >= 1 && c.Case_Rank__c <= 10) {
                    c.Case_Rank__c = c.Case_Rank__c - 1;
                } else {
                    c.Case_Rank__c = null;
                }
            }
            update cases;
        }
        return;
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/16/15
    * @brief:       The IncreaseCaseRank method provides the logic required to properly
    *                   increase or null out the ranks of the Cases assigned the the developer.
    * @return:     Void
    ***************************************************************************************/
    private void IncreaseCaseRank(List<Case> cases) {
        // if the list of Cases passed in by the ModificationLogic method isn't empty then it will iterate through the
        // list and increase their ranks by 1 or null out the rank if it is not within the acceptable limits (1-10).
        if (!cases.isEmpty()) {
            for (Case c : cases) {
                if (c.Case_Rank__c >= 1 && c.Case_Rank__c < 10) {
                    c.Case_Rank__c = c.Case_Rank__c + 1;
                } else {
                    c.Case_Rank__c = null;
                }
            }
            update cases;
        }
        return;
    }
}

Trigger Handler Test Code -

/***************************************************************************************
* @author:      Michael *REDACTED*
* @email:        michael.*REDACTED*@*REDACTED*.com
* @date:         11/24/15
* @brief:         This is the test class for the CaseRankTriggerHandler class
***************************************************************************************/
@isTest
public with sharing class CaseRankTriggerHandlerTest {
    // class level variables
    static User testRequestor = createTestRequestor();
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/24/15
    * @brief:       The InsertCase_NewRankNull test method ensures that the insert functionality of the
    *                   CaseRankTrigger is working as intended when a new Case is inserted with a null rank.
    ***************************************************************************************/
    @isTest
    static void InsertCase_NewRankNull() {
        // creates the initial case load for 'Test Developer' by passing in a list of integers that will become the ranks for the cases
        createDeveloperCase_Multiple(new List<Integer> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        // starting the test by inserting a new Case with a null rank
        Test.startTest();
        createDeveloperCase_Single('Null', null);
        Test.stopTest();
        // queries the system to create a map of Cases assigned to 'Test Developer' that are keyed by Rank with Subject as the value
        Map<Decimal, String> caseMap = createCaseMap();
        // system asserts to ensure that Cases are in the proper order
        System.assertEquals('Test Case (1)', caseMap.get(1), 'Test Developer should have \'Test Case (1)\' as rank 1 but instead has ' + caseMap.get(1));
        System.assertEquals('Test Case (2)', caseMap.get(2), 'Test Developer should have \'Test Case (2)\' as rank 2 but instead has ' + caseMap.get(2));
        System.assertEquals('Test Case (3)', caseMap.get(3), 'Test Developer should have \'Test Case (3)\' as rank 3 but instead has ' + caseMap.get(3));
        System.assertEquals('Test Case (4)', caseMap.get(4), 'Test Developer should have \'Test Case (4)\' as rank 4 but instead has ' + caseMap.get(4));
        System.assertEquals('Test Case (5)', caseMap.get(5), 'Test Developer should have \'Test Case (5)\' as rank 5 but instead has ' + caseMap.get(5));
        System.assertEquals('Test Case (6)', caseMap.get(6), 'Test Developer should have \'Test Case (6)\' as rank 6 but instead has ' + caseMap.get(6));
        System.assertEquals('Test Case (7)', caseMap.get(7), 'Test Developer should have \'Test Case (7)\' as rank 7 but instead has ' + caseMap.get(7));
        System.assertEquals('Test Case (8)', caseMap.get(8), 'Test Developer should have \'Test Case (8)\' as rank 8 but instead has ' + caseMap.get(8));
        System.assertEquals('Test Case (9)', caseMap.get(9), 'Test Developer should have \'Test Case (9)\' as rank 9 but instead has ' + caseMap.get(9));
        System.assertEquals('Test Case (10)', caseMap.get(10), 'Test Developer should have \'Test Case (10)\' as rank 10 but instead has ' + caseMap.get(10));
        System.assertEquals('Test Case (Null)', caseMap.get(null), 'Test Developer should have \'Test Case (Null)\' as rank null but instead has ' + caseMap.get(null));
        delete [SELECT Id FROM Case WHERE Resource_Assigned__c = 'Test Developer'];
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/24/15
    * @brief:       The InsertCase_NewRankNotNull test method ensures that the insert functionality of the
    *                   CaseRankTrigger is working as intended when a new Case is inserted with a rank that is not null.
    ***************************************************************************************/
    @isTest
    static void InsertCase_NewRankNotNull() {
        // creates the initial case load for 'Test Developer' by passing in a list of integers that will become the ranks for the cases
        createDeveloperCase_Multiple(new List<Integer> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        // starting the test by inserting a new Case with a null rank
        Test.startTest();
        createDeveloperCase_Single('NewNotNull', 4);
        Test.stopTest();
        // queries the system to create a map of Cases assigned to 'Test Developer' that are keyed by Rank with Subject as the value
        Map<Decimal, String> caseMap = createCaseMap();
        // system asserts to ensure that Cases are in the proper order
        System.assertEquals('Test Case (1)', caseMap.get(1), 'Test Developer should have \'Test Case (1)\' as rank 1 but instead has ' + caseMap.get(1));
        System.assertEquals('Test Case (2)', caseMap.get(2), 'Test Developer should have \'Test Case (2)\' as rank 2 but instead has ' + caseMap.get(2));
        System.assertEquals('Test Case (3)', caseMap.get(3), 'Test Developer should have \'Test Case (3)\' as rank 3 but instead has ' + caseMap.get(3));
        System.assertEquals('Test Case (NewNotNull)', caseMap.get(4), 'Test Developer should have \'Test Case (NewNotNull)\' as rank 4 but instead has ' + caseMap.get(4));
        System.assertEquals('Test Case (4)', caseMap.get(5), 'Test Developer should have \'Test Case (4)\' as rank 5 but instead has ' + caseMap.get(5));
        System.assertEquals('Test Case (5)', caseMap.get(6), 'Test Developer should have \'Test Case (5)\' as rank 6 but instead has ' + caseMap.get(6));
        System.assertEquals('Test Case (6)', caseMap.get(7), 'Test Developer should have \'Test Case (6)\' as rank 7 but instead has ' + caseMap.get(7));
        System.assertEquals('Test Case (7)', caseMap.get(8), 'Test Developer should have \'Test Case (7)\' as rank 8 but instead has ' + caseMap.get(8));
        System.assertEquals('Test Case (8)', caseMap.get(9), 'Test Developer should have \'Test Case (8)\' as rank 9 but instead has ' + caseMap.get(9));
        System.assertEquals('Test Case (9)', caseMap.get(10), 'Test Developer should have \'Test Case (9)\' as rank 10 but instead has ' + caseMap.get(10));
        System.assertEquals('Test Case (10)', caseMap.get(null), 'Test Developer should have \'Test Case (10)\' as rank null but instead has ' + caseMap.get(null));
        delete [SELECT Id FROM Case WHERE Resource_Assigned__c = 'Test Developer'];
    }
    /***************************************************************************************
    * @author:    Michael *REDACTED*
    * @email:      michael.*REDACTED*@*REDACTED*.com
    * @date:       11/24/15
    * @brief:       The createCaseMap method queries all the developers Cases then creates a map
    *                   keyed by Rank with the Subject as the value. This map will be used to ensure that
    *                   the Cases are in the proper order after any DML has been performed on a Case.
    * @return:    Map<Decimal, String>
    ***************************************************************************************/
    static Map<Decimal, String> createCaseMap() {
        List<Case> caseList = [SELECT Case_Rank__c, Subject FROM Case WHERE Resource_Assigned__c = 'Test Developer' ORDER BY Case_Rank__c];
        Map<Decimal, String> caseMap = new Map<Decimal, String>();
        for (Case c : caseList) {
            caseMap.put(c.Case_Rank__c, c.Subject);
        }
        return caseMap;
    }
    /***************************************************************************************
    * TEST DATA SECTION - Refactor out of test class after creating Test Data Factory
    ***************************************************************************************/
    static User createTestRequestor() {
        Profile testProfile = [SELECT Id from Profile where Name = 'Standard User'];
        User requestor = new User(FirstName = 'Test', LastName = 'Requestor', Alias = 'Test.Req', Email = 'newtestrequestor@null.com', UserName = 'newtestrequestor@null.com', ProfileId = testProfile.Id,
                                  TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US');
        insert requestor;
        return requestor;
    }
    static List<Case> createDeveloperCase_Multiple(List<Integer> ranks) {
        List<Case> developerCaseLoad = new List<Case>();
        Case developerCase;
        Integer count = 0;
        for (Integer rank : ranks) {
            count++;
            developerCase = new Case(Subject = 'Test Case (' + count + ')', Service_Request_Type__c = 'Development', Requestor__c = testRequestor.Id, Description = 'Foo', Business_Value_of_Change__c = 'Bar',
                                     Business_Area__c = 'Warranty', Requested_Implementation_Date__c = Date.today(), Resource_Assigned__c = 'Test Developer', Resource_Assigned_Email__c = 'newtestdeveloper@null.com', Case_Rank__c = rank);
            developerCaseLoad.add(developerCase);
        }
        for (Case c : developerCaseLoad) {
        }
        upsert developerCaseLoad;
        return developerCaseLoad;
    }
    static Case createDeveloperCase_Single(String name, Integer rank) {
        Case developerCase = new Case(Subject = 'Test Case (' + name + ')', Service_Request_Type__c = 'Development', Requestor__c = testRequestor.Id, Description = 'Foo', Business_Value_of_Change__c = 'Bar',
                                      Business_Area__c = 'Warranty', Requested_Implementation_Date__c = Date.today(), Resource_Assigned__c = 'Test Developer', Case_Rank__c = rank);
        upsert developerCase;
        return developerCase;
    }
}

Workflow Code - I didn't write this one, but click to see pic

CASE( Resource_Assigned__c ,
     "Kimberly REDACTED","foo@bar.com",
     "Josh REDACTED","foo@bar.com",
     "Robert REDACTED","foo@bar.com",
     "Jose REDACTED","foo@bar.com",
     "Ryan REDACTED","foo@bar.com",
     "Lloyd REDACTED","foo@bar.com",
     "Nathan REDACTED","foo@bar.com",
     "Amber REDACTED","foo@bar.com",
     "Ora REDACTED","foo@bar.com",
     "Jason REDACTED","foo@bar.com",
     "Shalini REDACTED","foo@bar.com",
     "Siva REDACTED","foo@bar.com",
     "Quinn REDACTED","foo@bar.com",
     "Adrienne REDACTED","foo@bar.com",
     "Vasantha REDACTED","foo@bar.com",
     "Michael REDACTED","foo@bar.com",
     "Sudheera REDACTED","foo@bar.com",
     "Test Developer","newtestdeveloper@null.com",
     "false")

I really appreciate any help you all can give me on this one!

Regards,
Michael

Mock a "blocking" method call with Spock?

Background

I'm learning to use Spock for unit testing and I've come across an issue I can't seem to get my head around:

Note: This example is very simplified, but it gets the idea of what I'd like to achieve across.

I have a class (call it Listener) which accepts a java.net.ServerSocket as a constructor parameter; it has a startListening method, which spawns a new thread which does the following (heavily reduced for brevity):

while(listening) {
    try {
        Socket socket = serverSocket.accept();
        doSomethingWithSocket(socket);
    } catch(IOException ex) {
        ex.printStackTrace();
        listening = false;
    }
}

In normal operation, the serverSocket.accept() call blocks until a connection is made to the ServerSocket.

Problem

I'd like to be able to test the interactions on the Socket returned by serverSocket.accept(). I can do this with Spock in the following way:

given: "A ServerSocket, Socket, and Listener"
    def serverSocket = Mock(ServerSocket)
    def socket = Mock(Socket)
    serverSocket.accept() >> socket
    def listener = new Listener(serverSocket)

when: "Listener begins listening"
    listener.startListening()

then: "Something should be done with the socket"
    // Verify some behavior on socket

At first glance, this works fine, except that every call to serverSocket.accept() will return the mocked Socket. Since this call is (intentionally) being invoked an indefinite number of times (because I want to accept an indefinite number of inbound connections) all of the interactions on the mock Socket occur an indefinite number of times (depending on how fast the machine is, how long it takes to run, etc...)

Using cardinality

I could use the cardinality of the interaction to specify at least one interaction, like so:

1.._ * socket.someMethod()

But something about that rubs me the wrong way; I'm not really looking for at least one interaction, I'm really looking for one interaction.

Returning null

I could do something like this (to return the Mocked socket once and then null):

serverSocket.accept() >>> [socket, null]

But then I still have tons of calls to doSomethingWithSocket that pass a null parameter, which I then have to check for and ignore (or report). If I ignore it, I might miss reporting a legitimate issue (I don't think ServerSocket#accept can ever return null, but since the class isn't final maybe someone implements their own version which can) but if I report it, my test logs get polluted with the log message that's reporting an expected outcome as an unexpected one.

Using closures and side-effects

I'm admittedly not a Groovy programmer by trade and this is the first time I've worked with Spock, so my apologies if this is a just plain wrong thing to do or if I'm misunderstanding something about how Spock does mocking

I tried this:

serverSocket.accept() >> socket >> {while(true) {}; null }

This loops forever before the accept method is even called; I'm not 100% sure why, as I didn't think the closure would be evaluated until the accept method was called a second time?

I also tried this:

serverSocket.accept() >>> [socket, { while(true){}; null }]

It's my understanding that when the accept method is called the first time, socket will be returned. Further calls will invoke the closure, which loops infinitely and should therefore block.

Locally, this appears to work, but when the build is run by a CI service (specifically, Travis CI) I still see test output indicating that the accept method is retuning null, which is a little bit confusing.

Am I just trying to do something that can't be done? This isn't a deal breaker for me or anything (I can live with noisy test logs) but I'd really like to know if this is possible.

Mockito: using a method in "thenReturn" to return a mock doesn't work

I have encountered what I assume might be a bug with Mockito, but was wondering if anyone else can shed light as to why this test doesn't work.

The full example class is here on pastebin, but I'm going to walk through it.

Basically, I have two objects, like this:

public class FirstObject {
    private SecondObject secondObject;
    public SecondObject getSecondObject() { return secondObject; }
}

public class SecondObject {
    private String name;
    public String getName() { return name; }
}

The first object is mocked via annotation and the before method:

@Mock
FirstObject mockedFirstObject;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

The second object is mocked in a method:

public SecondObject setupMockedSecondObject() {
    SecondObject secondObject = Mockito.mock(SecondObject.class);
    Mockito.when(secondObject.getName()).thenReturn("MockObject");
    return secondObject;
}

When "thenReturn" contains a direct call to this method to setup and obtain a mock of the second object, it fails:

@Test
public void notWorkingTest() {
    Mockito.when(mockedFirstObject.getSecondObject()).thenReturn(setupMockedSecondObject());
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

But when the mock returned by the same method is assigned to a local variable, which is used in "thenReturn", it works:

@Test
public void workingTest() {
    SecondObject mockedSecondObject = setupMockedSecondObject();
    Mockito.when(mockedFirstObject.getSecondObject()).thenReturn(mockedSecondObject);
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

Are we doing something wrong... or is this indeed a bug/limitation in Mockito? Is there a deliberate reason for this not working?

How do I add to the MediaStore for testing with Robolectric

My goal is to test some Android App code that gets a list of image files that are on the device and then does some work on that list.

I am new to Android and Android Unit testing.

I am attempting to add images to the MediaStore within a Robolectric unit test, but I am not sure how to proceed.

These are the steps I think I need to perform:

  1. Add the Test Images to a known directory on the local system.
  2. Copy the images to the Robolectric Temp directory that the Media Service will expect or can be pointed to.
  3. Then run insertImage and add the images to the MediaStore.

    MediaStore.Images.Media.insertImage(...);

When I attempt to insert the image however the method returns null.

I have images, but I am not sure where to copy them for the MediaStore to understand, and I am not sure why when I run the insertImage on a known image path I get a null return. I am not longer getting a FileNotFound exception so I believe it is finding the file.

Python 2.7 - Mutation Testing Tool suggestions

I have a system, whose modules are written in Python 2.7 and I'm given the task of proceeding with a mutation testing of some of the modules. I've done my research on the topic and now I'm getting on the tools. As long as I read, MutPy is considered to be the best (so far) developed tool for this kind of testing. The problem is, though, it is suitable for testing in Python 3.* versions.

Could somebody please help me with ideas for other tools for Python 2.7?

I was also thinking of converting the modules I need from 2.7 to 3.*, but I'm unsure if the system will somehow misbehave.

Any help will be appreciated, thank you.

Python Mocking Out Two File Open Contexts

I am trying to write some unit tests using mock for some code that looks like this:

# Write some text to edit to a file
with tempfile.NamedTemporaryFile(delete=False) as tf:
    tfName = tf.name
    tf.write(text_to_edit)

# Edit the text with vim
edit_file(tfName)

# Read edited text
with open(tfName, 'r') as f:
    text = f.read()

# Delete the file
os.remove(tfName)

# ... do stuff with text ...

This was my initial attempt at creating mock objects for that code:

@pytest.fixture
def mock_tempfile(mocker):
    new_tfile_obj = mock.MagicMock()
    tfile_instance = mock.MagicMock()
    tfile_instance.name.return_value = 'mockTemporaryFile'
    mocker.patch('tempfile.NamedTemporaryFile', new_tfile_obj)

    new_open = mock.MagicMock()
    fake_file = mock.MagicMock(spec=file)
    new_open.return_value = fake_file
    new_tfile_obj.return_value = tfile_instance
    mocker.patch('__builtin__.open', new_open)

    return (new_tfile_obj, tfile_instance, new_open, fake_file)
    # ... Code to mock edit_file/modify the temp file are in the actual test ...

However, I don't expect that to be anywhere near what should be used. I'm totally lost on how I would mock something like that.

Android Unit testing with AsyncTask

Hey everyone just getting started with Android testing and I am trying to test an async task. Here is the async task code. I am following this SO post Android AsyncTask testing with Android Test Framework. The runTestOnUiThread is not found in AndroidTestCase however. If I understand this correctly if its not run on the ui thread then the test finishes before the async task completes? Any help is greatly appreciated !

public class BackendTest extends AndroidTestCase {

    private static MyApi myApiService = null;
    private Context context;


    public void testAsyncJoke () throws Throwable{
        // create  a signal to let us know when our task is done.
        final CountDownLatch signal = new CountDownLatch(1);

        final AsyncTask<Pair<Context, String>, Void, String> myTask = new AsyncTask<Pair<Context, String>, Void, String>() {

            @Override
            protected String doInBackground(Pair<Context, String>... params) {
                if(myApiService == null) {  // Only do this once
                    MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                            .setRootUrl("http://ift.tt/1To3LcZ");
                    myApiService = builder.build();
                }

                context = params[0].first;
                String name = params[0].second;

                try {
                    return myApiService.sayHi(name).execute().getData();
                } catch (IOException e) {
                    return e.getMessage();
                }
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                signal.countDown();
            }
        };

        // Execute the async task on the UI thread! THIS IS KEY!
        runTestOnUiThread(new Runnable() {

            @Override
            public void run() {
                myTask.execute("Do something");
            }
        });

        signal.await(30, TimeUnit.SECONDS);

        // The task is done, and now you can assert some things!
        assertTrue("Happiness", true);
    }
}

How to not Mock an object when using Mockito and CDI?

I have an object reads configuration properties like this:

@ApplicationScoped
    public class Configuration {

    @Inject
    @Config(value = "endpoint.base", defaultValue = "http://localhost:52885/consumers")
private String base;

    public String getBase() { return base; } 

}

this object is injected to a service object like this:

public class LoyaltyService {

    final Sender sender;

    final Configuration config;

    @Inject
    public LoyaltyService(Sender sender, Configuration config) {
        this.sender = sender;
        this.config = config;
    }
} 

I am now testing this service object with Mockito. I want to mock the Sender object, but I don't want to mock the configuration, or at least I just want to use the default value defined inside the object.

How can I do that in a Test object?

For example, I tried the following:

public class LoyaltyServiceTest {

    @Mock
    private Sender sender;

    @Inject
    private Configuration config;

    private LoyaltyService target;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        when (sender.post(anyString(), anyString())).thenReturn("Post Success");
        target  =new LoyaltyService(sender, config);
    }
}

It doesn't seem CDI will register the Config object at all. How does this work? Thanks!

UIViewController lifecycle of topViewController in a UINavigationController not being simulated by beginAppearanceTransition:animated:

I'm writing unit tests for a bunch of view controllers hooked up with segues in a storyboard. The initial view controller is a UINavigationController.

I was interested in testing that a button in the topViewController, once tapped, performed some action (e.g. it invoked a method on a mock, for instance).

This requires the UINavigationController and its children to be loaded into the view hierarchy first.

I learned from at least two sources that you can call the viewController's beginAppearanceTransition:animated: is recommended by both:

The trouble is, when you invoke beginAppearanceTransition:animated: on a UINavigationController, the lifecycle methods (viewDidLoad, viewWillAppear:, viewDidAppear: etc.) don't get invoked for the topViewController.

That's really strange, because you'd think that loading the view of the navigation controller would necessarily require the top view controller to be loaded as well.

What can be done about this? My current workaround is just to load the view of the top view controller directly; but this is not ideal.

Async xUnit async unit tests are not visible

I use Visual Studio 2015 Ultimate, I wrote some unit test (I use xUnit 2.1.0.3179, it allow for this signature):

public async Task MyTest()

instead of standard unit test signature

public void MyTest()

but these unit tests are not visible in Visual Studio (code lens) and in Test Explorer. Of course I rebuild solution without any error :)

enter image description here

Is there any possibility to have the same feature like tests with standard signature? Maybe there is any VS extension?

Specta 'should receive' code

I'm trying to use Specta as my unit testing framework (Instead of Kiwi). How can I test if an object receives a selector Let's say 5 times, like I do in Kiwi?

In other words, what is the equivalent to this 'Kiwi' line of code:

[[sut should] receive:@selector(showUpsellIfNeededForFile) withCount:5];

Thanks in advance.

How to read grouped records in XamDataGrid when grouping is set programatically in tests?

I'm trying to write some test scenarios for the XamDataGrid. In these scenarios I'd like to set the grouping on a single Field. This code causes the grid to group as expected when I run the app and double-click the grid:

    Private Sub MyGrid_MouseDoubleClick(sender As Object, e As MouseButtonEventArgs) Handles MyGrid.MouseDoubleClick
        Dim xamDataGrid As XamDataGrid = CType(sender, XamDataGrid)
        Dim field As Field = xamDataGrid.FieldLayouts(0).Fields("A")
        Dim fieldSortDescription As New FieldSortDescription With {.Field = field, .Direction = ListSortDirection.Ascending, .IsGroupBy = True}

        xamDataGrid.FieldLayouts(0).SortedFields.Add(fieldSortDescription)
    End Sub

In tests, after running something very similar the Records and ViewableRecords collections do not reflect the grouping. xamDataGrid.ViewableRecords(0) is a DataRecord and not a GroupByRecord. Here's the code from the test:

    <TestMethod()>
    Public Sub Test()
        Dim xamDataGrid As New XamDataGrid

        xamDataGrid.DataSource = dataSource.DefaultView
        xamDataGrid.BeginInit()
        xamDataGrid.EndInit()

        Dim field As Field = xamDataGrid.FieldLayouts(0).Fields("A")
        Dim fieldSortDescription As New FieldSortDescription With {.Field = field, .Direction = ListSortDirection.Ascending, .IsGroupBy = True}
        xamDataGrid.FieldLayouts(0).SortedFields.Add(fieldSortDescription)

        ' exception thrown here because xamDataGrid.ViewableRecords(0) is a DataRecord
        Dim groupByRecord As GroupByRecord = CType(xamDataGrid.ViewableRecords(0), GroupByRecord)
        ' ...
    End Sub

How can the grid be refreshed or otherwise forced to reflect the grouping set by the code?

Thanks for your time.

Test Failed - Failed to set up the execution context to run the test

I am attempting to write unit tests for a set of classes that access or modify global variables.

The first global I needed to wrap up was:

extern std::atomic<Foo> GlobalFoo;

Where Foo is an enum class. I wrote 2 separate classes to handle the setting and getting of the value. I constructed unit tests that passed as expected. Within the test files I include variables to copy the global state (plus extra stateless objects that I may use for testing). I can then use these global copies for restoring values after each test. For example:

namespace Tests
{
    // Global save state
    const Framework::Foo originalGlobal = Framework::GlobalFoo;

    // Test constants
    const auto service = Framework::FooRetriever();
    const auto testFoo = Framework::Foo::SomeValue;

    TEST_CLASS(FooRetrieverUnitTests)
    {

        ...

The next global I started working on was:

extern const std::unordered_map<
    std::vector<char>, std::vector<char>, std::hash<std::vector<char>> GlobalBar;

I want to construct a class that is going to return a shared pointer to this global collection.

I start off by writing my test constants:

namespace Tests
{
    // Alias
    using Collection = const std::unordered_map<
        std::vector<char>, std::vector<char>, std::hash<std::vector<char>>;

    // Global state
    const std::shared_ptr<Collection> global = 
        std::make_shared<Collection>(Framework::GlobalBar);

    TEST_CLASS(FooRetrieverUnitTests)
    {
        // TODO
    };
}

However, running the test at this point produced the following message for all my tests (i.e. not just this new test):

Failed to set up the execution context to run the test

Commenting out the global allows all tests to run.

If I move the line commented as // Global state into a test method then the test will run without problem.

I looked into the error, but could not find anything that applied to my problem. I suspect the error message is masking the real problem. When I run the tests via command line I do not get any extra information. I was led to believe that it was possibly due to a missing DLL (although I found that hard to believe, seeing as I was merely using the standard library with no extras).

My project is a static library, and my unit tests are in the form of a DLL (this is the default approach used by Microsoft Visual Studio's unit testing framework).

Minus the usual "don't use globals" rant, I was wondering if anyone could provide some insight into the problem I am encountering. Perhaps I am doing something wrong by making a copy of the global collection in my Tests namespace or there is another bug in Visual Studio's unit testing feature.

The code compiles without error or warnings but the unit tests will not run in this state.

Python unittest extension module relative import 'proper' handling

Given a module setup as follows:

myproject
├── MANIFEST.in
├── README.md
├── build
├── dist
├── examples
│   ├── __init__.py
│   ├── mypackage-example.py
│   ├── mypackage-simple-v1.py
│   ├── mypackage-simple-v2-report.py
│   └── mypackage-simple-v2.py
├── mypackage
│   ├── PKG-INFO
│   ├── __init__.py
│   ├── api_methods.py
│   ├── config.py
│   ├── connector.py
│   ├── contrib.py
│   ├── examples
│   │   ├── __init__.py
│   │   ├── mypackage-example.py
│   │   ├── mypackage-simple-v1.py
│   │   ├── mypackage-simple-v2-report.py
│   │   └── mypackage-simple-v2.py
│   ├── qcache
│   │   ├── __init__.py
│   │   └── redis.conf
│   ├── mypackage.egg-info
│   │   ├── PKG-INFO
│   │   ├── PKG-INFO.bak
│   │   ├── PKG-INFO.bak-e
│   │   ├── SOURCES.txt
│   │   ├── dependency_links.txt
│   │   ├── requires.txt
│   │   └── top_level.txt
│   ├── settings.py
│   ├── setup.cfg
│   ├── tests
│   │   └── test_qualys_cache.py
│   ├── util.py
│   └── version.py
└── setup.py

where I want to have tests within mypackage.tests I am having issues with dependent relative imports on the qcache extension module. The module depends on (and must depend on) the parent module. I was attempting to bring in parent module requirements via relative imports as follows:

from .. import api_methods, connect

Which works from the top-level project path, but not from within the module itself. Am I doing this right for pypi standard unit tests? I'm really new to writing pypi eggs so any advice here is appreciated.

Right now I'm running my tests as follows (from the project, not package directory)

python -m unittest mypackage.tests.test_qualys_cache

Unit testing directives with nested dependencies

I am an angularJS beginner and I am trying to unit test a directive that has nested dependencies, I have tried different things but the service is always undefined. How do i go about this, I have given the structure of my code below.

  app.directive('directive1', function($compile, service1){
     return {
        restrict : 'EA',
        templateURL: 'directive1.html',
        scope: {

        },
        link: function(scope, element, rootScope){

        },
        controller: function($scope, $element,$rootScope){
        }
    }
 });

First service

apps.factory('service1', function($q, $http, service2){

}

second service

apps.factory('service2', function($q, $http, service3){

}

third service

apps.factory('service3', function($q, $http){

}

How to specify a relative date in yaml fixtures for RoR unit tests

I'm writing unit test using fixtures in yaml for a ruby on rails project.

We have many tests for users being < or > to n year old. ex:

young_kid:
  id: 2
  firstname: Nano
  lastname: Shinonome
  email: imarobot@nichijou.jp
  birthdate: 2000-05-11

Is there a way to specify a relative date like 2.days.from_now So that our tests are not bound to fail once the threshold is reached ?

We're using vanilla RoR unit tests.

Rspec: testing cancan ability with arguments

I am using cancan gem.

I have ability defined in my class:

module Gexcore
   class Myability
       include CanCan::Ability

    def initialize(user)
       can :delete_user, User do |victim|
      ..
        end
    end

  end
end

I am testing the ability to delete user with RSpec:

RSpec.describe "Permissions to delete user", :type => :request do
  describe 'del user' do
    it 'superadmin can delete user' do
      superadmin = double(User, :id => 10, <<some other fields>>)

      ability = Mymodule::Myability.new(superadmin)

      victim = double(User)

      res = superadmin_ability.can?(:user_del, victim)

      expect(res).to eq true

    end
  end

end

My user model: class User < ActiveRecord::Base delegate :can?, :cannot?, :to => :ability ... end

But it doesn't see method can? :delete_user, User from my ability. It expects User class but RSpec calls it with RSpec::Mocks::Double class.

How to test correctly ability from cancan gem using Rspec mocks ?

How to test private method using PowerMock which has object creation?

I have encapsulated the object creation into new method as specified in http://ift.tt/1tcXHI0 [Pattern 1: using one-line methods for object creation]

I have used private before makeFoo method. Which is making my work harder.

Wasn't private necessary for makeFoo method? If so how people handled it?

VC++ unit test project failed to set up the execution context to run the test due to possible missing dll

VC++ Newbie here:

I am attempting to TDD a project that uses a third party library (specifically AutoDesk's ObjectARX).

I have been able to create a dummy solution with a unittest project and a helloworld ARX project. I can successfully test a dummy method, everything is cool.

But when I call anything from the ObjectARX libraries the unit tests fail with

Failed to set up the execution context to run the test

After digging about and using Dependency Walker I found that the compiled dll is not able to find acdb21.dll which is named the same as one of the ARX libraries. It's expecting to find it in the same folder as the compiled dll.

I do not have an acdb21.dll, only the .h and .lib files. My understanding is that they should be compiled into the dll.

The linker happily finds the .h and .lib files so AFAICT the include and library paths are all set correctly.

Is the missing dll reported by Dependency Walker a red herring? Is something else amiss?

How to use for/ while loop in XCTesting? or how to do iterations in UI Testing

I want to drag drop all the cells in a tableview in UItesting.

so i want to know how to use for/ while loop in XCTesting? or how to do iterations in UI Testing

MOQ dictionary wrapper not returning mocked content

I have a class called CacheHelper that contains a ConcurrentDictionary property. I want to mock the return values. The dictionary itself is also mocked so that it returns an object when the index getter is used. When I call the dictionary directly I get the mocked item. But when I call the CacheHelper to get the same mocked dictionary, and then call the getter on the dictionary a different item is returned. I do not understand why this is. See code below

Guid dataFileId = Guid.NewGuid();
DataFile dataFile = new DataFile() { Id = dataFileId };
var myRepo = new Mock<DataFilesRepository>();
myRepo.Object.DataFiles.Add(dataFile);
var myDict = new Mock<MockConcurrentDictionary<Guid, DataFilesRepository>>();
myDict.SetupGet(x => x[It.IsAny<Guid>()]).Returns(myRepo.Object);
var cacheHelper = new Mock<CacheHelper>();
cacheHelper.Setup(x => x.CacheDataFiles).Returns(myDict.Object);

So when I call myDict.Object[new Guid()] I get the dataFile that I put in the Setup function. When I call cacheHelper.Object.CacheDataFiles[new Guid()] I get the item that is added by default in the MockConcurrentDictionary constructor.

Extra information: I use my own MockConcurrentDictionary to be able to return true when ContainsKey is called on the dictionary. The reason for this is so I can still do my state checks in my unit test. See definition of the MockConcurrentDictionary below.

public class MockConcurrentDictionary<TKey, TValue> : ConcurrentDictionary<TKey, TValue>
{
    public MockConcurrentDictionary() : base(new AlwaysTrueEqualityComparer<TKey>())
    {
        // If we do not add a item to the dictionary then it will not call Equals after a ContainsKey call.
        // Our AlwaysTrueEqualityComparer would have no use than.
        TKey key = (TKey)Activator.CreateInstance((typeof(TKey)));
        TValue value = (TValue)Activator.CreateInstance((typeof(TValue)));
        this.TryAdd(key, value);
    }

    public MockConcurrentDictionary(TValue value) : base(new AlwaysTrueEqualityComparer<TKey>())
    {
        // If we do not add a item to the dictionary then it will not call Equals after a ContainsKey call.
        // Our AlwaysTrueEqualityComparer would have no use than.
        TKey key = (TKey)Activator.CreateInstance((typeof(TKey)));
        this.TryAdd(key, value);
    }

    public virtual new TValue this[TKey key]
    {
        get { return base[key]; }
        set { base[key] = value; }
    }
}

How to prevent RSpec helper from being loaded

I'm writing integration tests with Capybara at the moment for our Rails 4 application. To make this as light-weight as possible, I have written a capybara_helper.rb file that is located inside the spec folder to be used with RSpec.

However, this file is loaded every time when the RSpec tests are running, destroying the configuration for existing Capybara tests that originally were present inside the test suite.

Is there a way to tell/configure RSpec to not load this file when starting up the "normal" unit tests?

My Integration tests are loaded with the command RAILS_ENV=test bundle exec rspec --tag @type:capybara. Our normal tests are just ran using rake parallel:spec[4]

How to include chutzpah test cases in tests project to output folder

I have a web project, say 'WebProj' in which I have defined all the my javascript source files with angular code. I am defining my chutzpah unit test cases for those javascript source files in another project 'WebProj.Tests' along with my other C# test cases. I am having both the web and tests project under same solution.

My problem is that when I try to integrate the web project to the TFS build process I cannot run the chutzpah test cases as the web project output folder don't have the chutzpah test case files copied to the project output folder. At the same time the test cases are executed if I have the chutzpah test cases defined in the same web project.

How can I execute the javascript chutzpah test cases on build process if those are defined in a separate Test project and include them in project output folder after build?

Angularjs+ jasmine test returns zero length

I'm calling a service in my unit test. The service seems to be available and the method is defined. I've created and spy and when I call the method I'm not receiving errors. When I try to access the response of the service call I get zero length (there are 2 records).

What am I missing?

describe("can I initialise the object  ", function () {
        var myMethodToCallDataService;

        beforeEach(function(){
            module(moduleName);
            module('services');
            inject(function($injector, _$controller_, _$rootScope_){
                $controller = _$controller_;
                $rootScope = _$rootScope_;
                myMethodToCallDataService = $injector.get('myMethodToCallDataService');
            });
        });

        it("myMethodToCallDataService should be defined", function () {
            expect(myMethodToCallDataService).toBeDefined();
        });

        it("myMethodToCallDataService should call the mt", function () {
            scope = $rootScope.$new();
            spyOn( myMethodToCallDataService, 'myMethodToCall' );
            myMethodToCallDataService.myMethodToCall();
            expect(myMethodToCallDataService.myMethodToCall).toHaveBeenCalled();
            scope.$apply();
            expect(myMethodToCallDataService.myMethodToCall.length).toBeGreaterThan(1);
        });
    });

How can I perform mutation tests on an F# codebase?

What options are available for me to execute mutation tests on an F# codebase?

For example, are there any frameworks available?

angularjs how to call service method inside jasmine unit test

I'm wanting to call a service method inside my jasmine unit test. I've been looking around and there are many ways, it seems to call a method that returns a promise.I'd like to call the service method and read the response back or at least test it. Whats the best way to call the service and get back the response in my unit test?

describe("can I call a service method  ", function () {
        var getMyservice;

        beforeEach(function(){
            module(moduleName);
            module('myservice.dependency');
            inject(function($injector, _$controller_, _$rootScope_){
                $controller = _$controller_;
                $rootScope = _$rootScope_;
                getMyservice = $injector.get('getMyservice');
            });
        });

        it("getMyservice should be defined", function () {
            expect(getMyservice).toBeUndefined();
        });



    });

"Lost connection to test manager service" when running unit tests in Xcode

Always every time I run unit tests inside the iOS simulator from Xcode a random test fails with "Lost connection to test manager service". What does this mean? Is it possible to fix it?

Error running XUnit tests in VS2013 / ReSharper 8 - xunit.dll not found

I've upgraded all the xUnit NuGet packages in my solution to XUnit 2.1 in the hope of fixing some problems I had running my xUnit tests, but I'm getting the same problem as before, which is:

[Window Title] Unit Test Runner

[Main Instruction] Unit Test Runner failed to run tests

[Content] System.ArgumentException: Could not find file: C:\Users\myuser\mysolution\myproject\bin\Debug\ xunit.dll

[Expanded Information] at Xunit.ExecutorWrapper..ctor(String assemblyFilename, String configFilename, Boolean shadowCopy) at XunitContrib.Runner.ReSharper.RemoteRunner.TestRunner.Run(XunitTestAssemblyTask assemblyTask, TaskProvider taskProvider) at XunitContrib.Runner.ReSharper.RemoteRunner.XunitTaskRunner.ExecuteRecursive(TaskExecutionNode node) at JetBrains.ReSharper.TaskRunnerFramework.StartupTaskRunnerHost.Execute(TaskExecutionNode node)

I've tried un-installing, re-installing, cleaning and rebuilding, etc. etc. for hours and got nowhere.

I'm using Visual Studio 2013 update 5, ReSharper 8.2.1, and have installed the following NuGet packages:

<package id="xunit" version="2.1.0" targetFramework="net451" />
<package id="xunit.abstractions" version="2.0.0" targetFramework="net451" />
<package id="xunit.assert" version="2.1.0" targetFramework="net451" />
<package id="xunit.core" version="2.1.0" targetFramework="net451" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net451" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net451" />
<package id="xunit.MSBuild" version="2.0.0.0" targetFramework="net451" developmentDependency="true" />
<package id="xunit.runner.msbuild" version="2.1.0" targetFramework="net451" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net451" />

To be fair, there is no file called xunit.dll in the bin folder, but... I've installed everything I can find, and I'm at a loss as to what else I can do.

Suggestions very welcome.

FakeItEasy failed assertion with randomly

I'm trying to implement a unit test with a methodcall assertion. (MustHaveHappened)

I'm using the following code:

[Fact]
        public void Should_set_setting_and_map_new_value_for_non_existing_setting()
        {
            //Arrange
            var userSetting = new SettingDetailsBuilder().Build();
            var respository = A.Fake<ISettingsRepository>();
            A.CallTo(() => respository.GetUserSetting(0, 0, null)).WithAnyArguments().Returns(userSetting);
            var dataretriever = new SettingsDataRetriever(respository);

            //Act
            var newUserSetting = dataretriever.SetUserSetting("variableName", "SomeOtherValue", 1, 1, "FST");

            //Assert
            A.CallTo(() => respository.GetUserSetting(1, 1, "variableName")).MustHaveHappened();
        }

But I get randomly a failed test, whereby some arguments are mentioned as "ignored". However, the assertion is with exact parameters.

Error:

Assertion failed for the following call:
    AlfaProNext.Repositories.Settings.ISettingsRepository.GetUserSetting(1, <Ignored>, <Ignored>)
  Expected to find it at least once but found it #0 times among the calls:
    1: AlfaProNext.Repositories.Settings.ISettingsRepository.Exists(varName: "variableName")
    2: AlfaProNext.Repositories.Settings.ISettingsRepository.GetUserSetting(
          userId: 1,
          profileId: 1,
          variableName: "variableName")

Does anybody knows why this is happening randomly?

Skip a method execution to unit test controller flow

public class DemoController : Controller
{


    private readonly ICommonOperationsRepository _commonRepo;

    public DemoController (ICommonOperationsRepository commonRepo)
    {
       _commonRepo = commonRepo;
    }
    public ActionResult Default()
    {
       var model = new DemoModel();
       try
       {
           **ConcreteClass cc = new ConcreteClass(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());
            cc.ConcreteClassMethod();**

           model.ListTopListing.AddRange(_commonRepo.GetListings());
        }
        catch (Exception ex)
        {
            ExceptionHandler objErr = new ExceptionHandler(ex, "DemoController .Default()\n Exception : " + ex.Message);
            objErr.LogException();
         }
         return View(model);
     }

}

I am trying to unit test my controller. ConcreteClass constructor and its method ConcreteClassMethod both have some dependency on HttpRequest variables which i am not able to pass from my unit tests.

I want a way by which i can simply skip execution of ConcreteClass's constructor and ConcreteClassMethod when I am calling Default action of DemoController.

Why does Visual Studio use a different output directory for a) normal unit tests and b) data driven unit tests?

At first we only had a couple of data constellations we used to regularly test. Those we tended in the testcode having a couple arrays of data and looping through those to run tests.

Now that we have huge DataSources (namely Excel-Files) that contain 100s of data rows that are to be run through our unit tests we used the VisualStudio.TestTools to configure according DataSources:

<configSections>
  <section name="microsoft.visualstudio.testtools" 
           type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>

<connectionStrings>
  <add name="KradTestConnection" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Beitragstests_KRAD_Tarif2016.xls;Extended Properties=Excel 12.0 Xml" providerName="System.Data.OleDb" />
  <add name="PkwTestConnection" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Beitragstests_PKW_Tarif2016.xls;Extended Properties=Excel 12.0 Xml" providerName="System.Data.OleDb" />
</connectionStrings>

<microsoft.visualstudio.testtools>
  <dataSources>
    <add name="KradTestDataSource" connectionString="KradTestConnection" dataTableName="TestInput" dataAccessMethod="Sequential"/>
    <add name="PkwTestDataSource" connectionString="PkwTestConnection" dataTableName="TestInput" dataAccessMethod="Sequential"/>
  </dataSources>
</microsoft.visualstudio.testtools>

With that we just provided the data files 'Beitragstests_KRAD_Tarif2016.xls' and 'Beitragstests_PKW_Tarif2016.xls' and decorated our testcases with the DeploymentItemAttribute:

[DataSource("PkwTestDataSource")]
[DeploymentItem("Beitragstests_PKW_Tarif2016.xls")]
[TestCategory("DataDriven Berechnungstests")]
[TestMethod]
public void Pkw_HaftplichtMitVollkasko_TestCases() { ... }

So far and only testing those 'data driven unit tests' we had no problems. But our Test-Suite does contain many older testclasses we still require.

If we run data-driven and non-data-driven tests in a seperate test session, everything works out fine and all tests are 'green'.

As soon as we run "ALL" testcases though, many of the non-data-driven tests fail.

Analyzing that behaviour quickly made us aware that - be it mstest or running the tests via resharper (and yes, we disabled 'shadow-copying' in resharper-test-options) - as soon as the data-driven testcases are included in a test session, the tests wont be run in the projects output directory $OutDir that we defined for many projects and solutions (which each deliver a part of the dlls required for our testing suite). Running the data-driven testcases will cause Visual Studio to create a new directory 'TestResults/Deploy_ /Out' located next to the solution file '...sln' instead... in which of course the TestRunner will not find dependent DLLs that are delivered to our $OutDir.

Could anyone please explain to me, why the test engine creates different output directories based on the inclusion of 'data-driven unit tests' into a test session?`

Would anyone have a hint or even a solution about how to get Visual Studio to use the directory $OutDir that we configured in our projects instead of creating a new 'TestResults/Deploy_ /Out' every time?

Thanks in advance!

I'm creating my test using CTF and I'm receiving the following error

org.mule.tools.devkit.ctf.exceptions.PlatformManagerException: Can not initialize Platform Manager at org.mule.tools.devkit.ctf.platform.AbstractPlatformManager.initialize(AbstractPlatformManager.java:60) at org.mule.tools.devkit.ctf.mockup.ConnectorTestContext.initialize(ConnectorTestContext.java:98) at org.mule.tools.devkit.ctf.mockup.ConnectorTestContext.initialize(ConnectorTestContext.java:79) at org.mule.modules.jbpm.automation.runner.FunctionalTestSuite.initialiseSuite(FunctionalTestSuite.java:33) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.lang.RuntimeException: java.lang.NullPointerException at org.mule.tools.devkit.ctf.handlers.EmbeddedMethodExecutionHandler.onStart(EmbeddedMethodExecutionHandler.java:148)

I am using Devkit 3.7.1, CTF 0.9.4.

Thanks in advance.

TFS unit test passes on build machine but fails on TFS-Build

I have a unit test that fails when it is run by TFS-build, while it passes when I run it on the build machine (through Visual Studio) [It passes on my local machine too]

Does anyone have any information or tips for this issue?

Phaser game test

I am currently developing a javascript game with the Phaser Framework. I would like to perform unit tests on my game. In order to test this game I need to simulate the creation of a state Phaser.Game. Would you ways to help me in my approach? Thank you in advance !

dimanche 29 novembre 2015

How to mock GetView operation of couchbase .net SDK

I am trying to write unit test for a method which executes a view on the couch base server using .NET SDK, but unable to mock the o/p.

Method :-

  public int CountJsonDocs()
        {
            int savedFiles = 0;
            var viewResult = _couchbaseClient.GetView("GetAllDocs", "GetAllDocuments");
            if (viewResult.TotalRows > 0)
            {
                foreach (var viewRow in viewResult)
                {
                    var jsonData = viewRow.GetItem();
                    savedFiles++;
                }
            }
            return savedFiles;
        }

GetView() method returns an object of type IView

how can I pass argument(s) through nose.run that can be picked up by list of python test files containing test methods

I am creating a series of tests with python unittest and executing them with nosetest module.

I am trying to figure out how do i pass an argument(s), for example environment or domain, so that the value would be passed the actual test method being executed.

I have a runner python script which passes test suite class file and environment as arguments

python runner.py --suite=generic_pass.py --env=dev.domain.com

The runner.py picks up the suite value and passes it to test_suite in nose.run method within "runner.py"

Contents of runner.py

nose.run(argv=["", test_suite, "--verbosity=2"])

The contents of test_suite or "generic_pass.py" script are as follows

class loginTest(login.userLoginTest):
     pass
class logoutTest(logout.userLogoutTest):
     pass

The contents of login.py

class userLoginTest(unittest.TestCase):
     def setUp(self):
         self.login = userLogin(user,pass,environment)
     def test_response(self):
         self.assertEquals(200, getResponse(self.login))

When python runner.py script is executed, it then runs nose.run, which then executes the tests specified in generic_pass.py (test_suite)

I am trying to figure out, how can i pass the contents of --env "dev.domain.com" from runner.py to each test case class file though nose.run() method, so that i could use it in

self.login = userLogin(user,pass,environment)

which is located in login.py