dimanche 31 juillet 2016

How to test code that calls top level functions in Kotlin?

I am very new to Kotlin.

I have a class that calls a top level function (which makes a http call). I am trying to write unit tests for my class without having it go out to the network.

Is there a way to mock/powermock/intercept the call from my class to the Kotlin top level function?

class MyClass {
    fun someMethod() {
        // do some stuff
        "http://ift.tt/2akR97n".httpGet(asList("someKey" to "someValue")).responseString { (request, response, result) ->
            // some processing code
        }
    }
}

It is using the kittinunf/Fuel library for the httpGet call.

It adds a top level function to String that ultimately calls a companion object function in Fuel (Fuel.get()).

The unit test needs to intercept the call to httpGet so that I can return a json string for the test.

How to create Chai/Mocha unit tests for a ES6 class React component?

I'm having trouble creating Chai/Mocha unit tests for an ES6 class. This project is configured correctly to use chai/mocha, ES6, babel, so that's not the issue. (I can run a dummy test where I check if 2 variables are the same). The error only throws when I try to use the ES6 class React component below. I run the test using the command npm test. My package.json is configured to run this command when I run npm test:

mocha --compilers js:babel/register file/path/to/spec --recursive

I am getting this error:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the component

The ES6 class React component that looks like (obviously not all of it):

import ...

class Car extends React.Component {
  constructor() {
    super();
    this.state = {
      color: ''
    }
  }

  setColor(color) {
     this.setState({ color : color });
  }

  render() {
    .......
  }
}

The test/spec JS file looks (mostly like):

import ...

let should = chai.should();
describe('Car Test', () => {
  let car;

  beforeEach(() => {
    car = new Car();
  });

  it('should be red', () => {
    car.setColor('red'); // pretty sure THIS is throwing the error
  });
});

Expected invocation on the mock at least once, but was never performed

First of all, I googled all SO posts on this but none helped me. I get the exception on the subject on below piece.

 [Test]
    public void TestInv()
    {
        string inReference = "123";
        _Service.Setup(q=> q.InvoiceS(inReference ));
        _Service.Verify(q => q.InvoiceS(inReference ), Times.AtLeastOnce());
    }

unit test for ensuring a method inside a method is not called

I have two methods like below.

public bool IsSuccess()
{
   // Some logi
}

public bool ShouldSendLogic()
{
  var status = IsSuccess();
  if(status)
  {
    SendInvoice();
   // do some operation
  }
 return status;
}

Now I am writing integration/unit tests. I can call the ShouldSendLogic but I want to ensure SendInvoice is not called by setting the Success as false. (Just for negative case). How to write test case for this scenario, please help me with a code for this.

Test With Mocked Service And DateTime Fail Randomly

I am having a test that fail randomly on Bamboo. The ratio is like 1 fail every 10 builds. It never failed on my local environment.

Here my service semplified:

public final class TripAdvisorSwitchServiceImpl implements TripAdvisorSwitchService{

    private FfxProperties ffxProperties = FfxProperties.getInstance();

    private DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");

    @Reference
    private DateTimeService dateTimeService;

    @Override
    public boolean isEnabled() {
        String endDateStr = ffxProperties.get("tripadvisor.endDate");
        DateTime endDate;
        try {
            endDate = dateTimeFormatter.parseDateTime(endDateStr);
        } catch (IllegalArgumentException e) {
            LOG.error("Date format is wrong: {}", endDateStr);
            return true;
        }

        return dateTimeService.getCurrentDateTime().isBefore(endDate);
    }
}

And here my random failing test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FfxProperties.class)
public class TripAdvisorSwitchServiceImplTest {

    private DateTimeZone utcTimezone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"));

    @InjectMocks
    private TripAdvisorSwitchServiceImpl tripAdvisorSwitchService;

    @Mock
    FfxProperties ffxProperties;

    @Mock
    DateTimeService dateTimeService;

    @Before
    public void setup() throws IllegalAccessException {
        MockitoAnnotations.initMocks(this);
        mockStatic(FfxProperties.class);
        when(FfxProperties.getInstance()).thenReturn(ffxProperties);
    }

    @Test
    public void tripAdvisorShouldBeDisabledAfterTheEndDate() {
        when(ffxProperties.get("tripadvisor.endDate")).thenReturn("2010-09-14T14:00:00+0000");
        when(dateTimeService.getCurrentDateTime()).thenReturn(new DateTime(2016, 9, 14, 14, 1, 0, 0, utcTimezone));

        assertFalse("It should be disabled", tripAdvisorSwitchService.isEnabled());
    }
}

Any help is very much appreciated.

Test::Unit testing for Devise User::RegistrationController

I've been looking for how to setup testing for Devise 4.1.1 registration controller, I understand that this is not recommended, but for my application the registration controller has been customized particularly to pertain to our needs. We have only a few new columns to the users table that are getting saved during the sign up process, so I wouldn't assume that it is affecting the testing environment.

I also am aware that integration testing can be done to achieve this, however I am looking to do this with unit testing for now.

I have setup this section in the test_helper.rb as advised by Devise

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

#This is what I added:
class ActionController::TestCase
  include Devise::TestHelpers
end

I created a new file called registrations_controller.rb in the folder controllers/users/ because it did not already exist, and this is the contents:

require 'test_helper'

class Users::RegistrationsControllerTest < ActionController::TestCase
  setup do
    @request.env["devise.mapping"] = Devise.mappings[:user]
  end
  test "sign_up view" do
    get :new
    assert_response :success
    flunk("test flunk")
  end

end

When running rake test this is the output:

$ rake test
(in /home/www/dev)
Run options: --seed 163

# Running:



Finished in 0.010214s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

What am I missing here??

Combining EasyTest/JUnitParameter alike with ObjectMother pattern

I was wondering whether I can use annotations with tools like JUnitParameter with an Object mother pattern. For example.

class EmployeeObjectMother {
    @DataProvider(filepath = "ceoEmployee.csv") 
    public static Employee getCeoEmployee(@Param String name, @Param Double salary) {
        Employee employee = new Employee(name, salary);
        return employee;
    }
}

class EmployeeTest {

   // some annotation magic
   // parameter = EmployeeDataprover.getCeoEmployee 
   void shouldBeAnEmployee(Employee employee) {
       // do some testing
   }

}

In addition if it would be nice to have list of Employees through annotation magic such as:

   // annotation magic
   // annotation parameter parameter: List of employees and run for each of the item from the 
   // list
   void shouldBeAnEmployee(Employee employee) {
   }

I am not sure this is even possible or exists. If not then what is the way we can achieve Object Mother obtain its parameters and avoid coupling it with literal file name in its code. Please enlighten me.

Thanks

FluentAssertions Recursion Depth Reached in object with recursive structure

I'm trying to unit test an object that recursively represents a directory structure, but even at the simplest level the fluentAssertions ShouldBeEquivalentTo is failing with The maximum recursion depth was reached.

How should this test be written to correctly get the test to pass.

Additionally, if child nodes were added, how do I stop the ShouldBeEquivalentTo infinitely re-comparing the parent DirectoryNode?

Here is the code, it is using Xunit, FluentAssertions and System.IO.Abstractions libraries.

The test:

[Fact]
public void DirectoryTreeBuilder_BuildTree_String_TopNodeTest()
{
    // Arrange
    string path = "C:\\";

    var mockFileSystem = new MockFileSystem();
    mockFileSystem.AddDirectory(path);

    var expected = new DirectoryNode
    {
        Info = mockFileSystem.DirectoryInfo.FromDirectoryName(path),
        Children = new List<DirectoryNode>()
    };

    // Act
    var builder = new DirectoryTreeBuilder(mockFileSystem);
    var calculated = builder.BuildTree(path);

    // Assert
    calculated.ShouldBeEquivalentTo(expected);
}

DirectoryNode properties class:

public class DirectoryNode
{
    public DirectoryNode Parent { get; set; }
    public DirectoryInfoBase Info { get; set; }
    public List<DirectoryNode> Children { get; set; }
    public List<FileInfoBase> Files => Info.GetFiles().ToList();
}

Tree Builder:

public class DirectoryTreeBuilder
{
    private readonly IFileSystem fileSystem;

    public DirectoryTreeBuilder(IFileSystem fileSystem)
    {
        this.fileSystem = fileSystem;
    }

    public DirectoryTreeBuilder() : this(new FileSystem())
    {
    }

    public DirectoryNode BuildTree(string path)
    {
        var directoryInfo = fileSystem.DirectoryInfo.FromDirectoryName(path);

        return BuildTree(directoryInfo);
    }

    public DirectoryNode BuildTree(DirectoryInfoBase directoryInfo)
    {
        var node = new DirectoryNode
        {
            Info = directoryInfo,
        };

        var directories = directoryInfo.GetDirectories();
        var children = new List<DirectoryNode>();

        // Process list of child directories
        foreach (var directory in directories)
        {
            var child = BuildTree(directory);
            child.Parent = node;

            children.Add(child);
        }

        node.Children = children;

        return node;
    }
}

Dos and don'ts of testing a multi-step process

I have code which rewrites a context-free grammar into Chomsky Normal Form. I wish to test this, in particular with property testing. The code under test looks something like this:

chomsky_normal_form(cfg) do:
    intermediate_value_1 = step1(cfg)
    intermediate_value_2 = step2(intermediate_value_1)
    ...
    output step5(intermediate_value_4)

For each step there is a postcondition which should hold. There is also an invariant which should hold both before the first step and after each step. There is also a transition invariant which should hold for (cfg, iv1), for (iv1, iv2) etc. up to the last pair.

One approach to testing this is to write a method which asserts all of the postconditions and invariants.

One downside to this that I can spot is that I have to print out the failing values and the context of the test, instead of having the testing framework do some of that work for me.

It also appears to go against the spirit of property testing, but I can point to how exactly that would cause something undesirable to happen. Can you?

Another approach is to split this up into one test case (property) per aspect I want to test.

A downside is that there will be O(s^2) properties where s is the number of phases: one testing postcondition i after phase k for k=1..n and i=1..k. On top of this, n properties testing the transition invariants and n+1 testing the input-and-step invariant.

I can probably do this with code of length O(s), and without any duplication, but it seems very excessive even so.

To the extent I want to run many and/or large inputs through this gauntlet I would have to care about performance, and this looks like a lot of duplicated computations.

The question: what have you learned (from experience or otherwise) about the utility of either test approach? Is there some third approach I'm not seeing? Or is the answer just to suck it up and apply the elbow grease to test each step separately?

I think the best might be to have a framework which supports the first approach, in which I could accumulate a list of errors during the run, have the test fail if the list is non-empty, and have the framework present the list of errors in sensible ways; for property testing, it should also show contrasting pairs for the (non-)occurrence of each observed error. Does something like this exist? Am I right in wanting this, or would this be a bad idea for some reason I'm not seeing?

Practicalities: I'm writing this in Rust. Tool suggestions are welcome.

Irrelevant concrete details: the universal invariant I want to enforce is the welformedness of the representation of the context-free grammar (i.e. no dangling pointers). The post-conditions are that each step has done what it says on the tin, e.g. after the step which splits large right-hand-sides into smaller ones, all the right-hand sides are small. The step-transition invariant is that the language is preserved (which is undecidable, so I'll test strict preservation on finite languages and preservation of some sensitive features on more general language classes.)

Jasmine can't find namespace (internal module)

I'm trying to use jasmine to test functions of a typescript class.

My spec is test.ts (my gulp test task feeds the js to jasmine).

/// <reference path="../lib/bar.ts" />

import Bars = com.bar;

describe("Bartender test", function () {
    describe("See if I get served a drink", function () {
        var myBartender: Bars.Bartender = new Bars.Bartender();
        it("should serve a drink", function () {
            expect(myBartender.getBeer()).toEqual(<Bars.IDrink>{});
        });
    });
});

Bar uses namespace com.bar and looks like this:

namespace com.bar {
    export interface IDrink {
        volume: number;
    }

    export class Bartender {

        constructor() {

        }

        public getBeer(): IDrink {
            return <IDrink>{ volume: 1 };
        }
    }
}

When I run this test I get ReferenceError: com is not defined. Intellisense Visual Studio says all is fine.

My gulp task for test:

return  gulp.src('./src/spec/test.js').pipe(jasmine());

Does Jasmine need a list of js files even though they are referenced in the test?

Assert Error is thrown when mocking python3

I am trying to write a test that mocks raising PermissionError on a call to open() when attempting to open a file for reading. However I cannot seem to get the test working. The PermissionError appears to be thrown but my test fails because of this even though I am trying to assert it is thrown.

Below contains one of my attempts:

fileMethods.py

def readfile(myfile):
    with open(myfile, 'r') as file:
        filecontent = file.read()
    file.close()
    return filecontent

fileMethods_test.py

def test_readfile_throws_PermissionError(self):
    with mock.patch('fileMethods.open') as openMock:
        openMock.side_effect = PermissionError
        self.assertRaises(PermissionError, fileMethods.readfile('file_to_readin'))

Am I missing something obvious or is the way I am testing this method incorrect?

How to mock object from third party library at specific time

I'm trying to mock the reponse from urllib2.urlopen from the Clarifay Python client.

The reason for this is that I don't want to expend an API call while testing, since I want to check that everything works ok but just fake the response to the server when I try to tag images using their client.

Problem is that urllib2.urlopen is used BEFORE I make use of their method to tag images (mostly to check API configuration, Oauth credential, etc) which kinda breaks my whole thing since I cannot go forward.

So this is my testing code:

    # Patch the actual code that clarifai client uses
    with patch('clarifai.client.mime_util.urllib2.urlopen') as mock_get:
        # Configure the mock to return a response with an OK status code.
        fd = open('fixtures/dummy_clarifai_result.json', 'r')
        dummy_response = json.load(fd)
        fd.close()
        mock_get.return_value = dummy_response
        response = self.tagger.process_images_clarifai(folder_name='sample_images')
        self.assertIsNotNone(response)
        self.assertTrue(response.empty)

The clarifai client calls the mime_util module to actually call this method, that I'm interested to mock the response

def post_multipart_request(url, multipart_message, headers={}):
    data, headers = message_as_post_data(multipart_message, headers)
    req = RequestWithMethod(url, 'POST', data, headers)
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()
    return response

As I said, before the call to this method actually happens, the urlib2.urlopen is called in-between. Now I wonder if I can tell somehow to mock the object not the whole time but just when I want it...I really doubt it since just calling the tagging method executes this calling tree that in-between calls urlopen...

Also tried to mock directly that method (post_multipart_request) but I keep on getting errors with the path at the patch annotation...

Thanks!

QUnit not running external JavaScript file

I'm trying to adapt the tutorial here to use QUnit v2.x, but it doesn't seem to be picking up the JavaScript file I want to test.

test.html

<script src="http://ift.tt/wV40hO"></script>
<script src="qunit.js"></script>
<script src="../list.js"></script>
<script>

    QUnit.test("errors should be hidden on keypress", function (assert) {
        $('input').trigger('keypress');
        assert.equal($('.has-error').is(':visible'), false);
    });

</script>

list.js

jQuery(document).ready(function ($) {
    $('input').on('keypress', function () {
        $('.has-error').hide();
    });
});

The test fails with a result of true

The provided code in the tutorial works fine with QUnit 1.8

<script>

/*global $, test, equal */

test("errors should be hidden on keypress", function () {
    $('input').trigger('keypress');
    equal($('.has-error').is(':visible'), false);
});

test("errors not be hidden unless there is a keypress", function () {
    equal($('.has-error').is(':visible'), true);
});

</script>

How to get pressed key value in InputSimulator?

Hello i learn how to use unit testes.And try to simulate keypressing,for this reason i try to use InputSimulator Input Simulator CodePlex. I try to do something like this.

  Key key=inputSimulator.Keyboard.KeyPress(VirtualKeyCode.ESCAPE);
            switch (key)
            {
                case key.D1:
                   //Do something
                case key.D2:
                   //Do something
                case key.D3:
                   //Do something                 
                default:
                   //Do something    
            }
        }
        while (userChoice.Key != ConsoleKey.Escape);

So how to get pressed key value from inputSimulator.Keyboard.KeyPress(VirtualKeyCode.ESCAPE); method for using it in switch-case construct?

How to mock a publication in Meteor test

I'm using practicalmeteor/mocha package. Here I'm trying to test a subscription on a server side, but I cannot call the Publication. Can you guys suggest me a solution for this or a package to mock Publication. Below is the code that I write:

describe('Subscriptions test', () => { const userId = Random.id(); let sandbox;

    beforeEach((done) => {
      StubCollections.stub(PPDM_UNIT_CONVERSION);
      PPDM_UNIT_CONVERSION.insert({ FACTOR_NUMERATOR: 3.5 });
        sandbox = sinon.sandbox.create();
      done();
    })

    afterEach(() => {
      StubCollections.restore();
        sandbox.restore();
    })

    it('integration test - "core_exchange_rates" -  subscription', (done) => {
      const subs = Meteor.subscribe("core_exchange_rates", new Date(), 'RM');
        expect.(PPDM_UNIT_CONVERSION.findOne).to.be.above(0)
    });
});

PHPUnit error in babysteps

I am studying about TDD and I tried to run tests using phpunit in console, but the console return for me the follow error.

Fatal error: Class 'PHPUnit\Framework\TestCase' not found in E:\xampp\htdocs\estudos\phpunit\tests\MoneyTest.php on line 8

PHP Fatal error: Class 'PHPUnit\Framework\TestCase' not found in E:\xampp\htdocs\estudos\phpunit\tests\MoneyTest.php on line 8

How can I solve this ? I am using PSR-4 to create autoloader in this project

Link from repository with project: http://ift.tt/2aAvXer

Unittesting Django CreateView with mock library

I'm trying to test my CreateView by posting some data and mocking models' save() method.

class BaseViewTest(TestCase):
   def setUp(self):
       self.user = UserFactory()
       self.factory = RequestFactory()

class MuayeneCreateViewTest(BaseViewTest):

   def test_get(self):
        request = self.factory.get(reverse('muayene:create'))
        request.user = self.user

        response = MuayeneCreateView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertTrue('form' in response.context_data)
        self.assertTrue('muayene/muayene_form.html' in response.template_name)

    @patch('muayene.models.Muayene.save', MagicMock(name="save"))
    def test_post(self):
        hasta = HastaFactory()
        ilac1 = IlacFactory()
        ilac2 = IlacFactory()
        data = {
            'hasta': hasta.id,
            'tarih': str(datetime.date.today()),
            'yakinma': 'Kusma',
            'kullandigi_ilaclar': [ilac1.id, ilac2.id],
            'öntani_tani': 'Öntanı ve tanı',
            'öneri_görüsler': 'Öneri ve Görüşler',
            'özel_notlar': 'Özel notlar'
        }

        request = self.factory.post(reverse('muayene:create'), data)
        request.user = self.user

        response = MuayeneCreateView.as_view()(request)

        self.assertEqual(response.status_code, 302)

        self.assertTrue(Muayene.save.called)
        self.assertEqual(Muayene.save.call_count, 1)

Here is MuayeneCreateView:

class MuayeneCreateView(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    model = Muayene
    form_class = MuayeneCreateForm

and traceback:

ERROR: test_post (tests.test_muayene.MuayeneCreateViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python3.5/unittest/mock.py", line 1157, in patched
    return func(*args, **keywargs)
  File "/home/egegunes/Dropbox/Programs/hastatakip/tests/test_muayene.py", line 153, in test_post
    response = MuayeneCreateView.as_view()(request)
  File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch
    return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 256, in post
    return super(BaseCreateView, self).post(request, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 222, in post
    return self.form_valid(form)
  File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 201, in form_valid
    self.object = form.save()
  File "/usr/lib/python3.5/site-packages/django/forms/models.py", line 452, in save
    self._save_m2m()
  File "/usr/lib/python3.5/site-packages/django/forms/models.py", line 434, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related.py", line 1618, in save_form_data
    setattr(instance, self.attname, data)
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 480, in __set__
    manager = self.__get__(instance)
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 468, in __get__
    return self.related_manager_cls(instance)
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 751, in __init__
    (instance, self.source_field_name))
ValueError: "<Muayene: ID: None - 2016-07-31 - Bob Baz>" needs to have a value for field "muayene" before this many-to-many relationship can be used.

I couldn't figure out what causes this error. Muayene instance is used by some other models with ManyToManyField but IMO this error must not show up unless I try to create one of those models with this instance.

Unit Testing IStringLocalizer

I'm having difficulties trying to unit test my ASP.NET Core controllers. I'm building on .NET Core 1.0 and I use xUnit + Moq for testing. Service tests work just fine, with an InMemory EF DbContext and DI all over the place.

Now I'm trying to test my controllers and all of our controllers have constructor injection like this:

public HomeController(
        IStringLocalizer<HomeController> localizer,

All the other dependencies get resolved correctly and everything works. But I can't get IStringLocalizer to work properly.

If I try to register a dependency in my Services collection and get an instance through DI, then I get an exception saying IHostingEnvironment couldn't be resolved. And I don't want to use a test server or anything, I'm focusing on unit tests for now.

I tried to mock the IStringLocalizer but that didn't work either, it results in a null value.

I'm kinda new to unit testing and .NET Core testing in general, so It's most probably a much simpler issue and it's just that I don't know how to mock and write unit tests correctly. Any help is much appreciated, thanks in advance.

Laravel 5.1 - Why unit testing authentication fails with a model factory?

So using the factory method the 1st and 3rd test fail.

<?php

class AuthTest extends TestCase
{
     public function setUp()
     {
         parent::setUp();

         $this->artisan('migrate');
         //$this->artisan('db:seed');
         $user = factory(RMS\User::class, 'admin')->create([
             'email' => 'admin@abc.co.za',
             'password' => bcrypt('secreT5000'),
          ]);

          $normal_user = factory(RMS\User::class)->create([
              'email' => 'company@abc.co.za',
              'password' => bcrypt('secreT5000'),
           ]);
     }

     public function tearDown()
     {
         $this->artisan('migrate:reset');
     }

    /**
     * Test Successful Login
     *
     * @return void
     */
    public function testGoodAdminLogin()
    {
      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->check('remember')
         ->press('Login')
         ->seePageId('/dashboard')
         ->dontSee('These credentials do not match our records.')
         ->see('Users');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testFailedLogin()
    {
      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT', 'password')
         ->press('Login')
         ->see('These credentials do not match our records.')
         ->seePageIs('/auth/login');
    }

    /**
     * Test Normal user positive Login
     *
     * @return void
     */
    public function testNormalUserLogin()
    {
      $this->visit('/admin')
         ->type('company@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->press('Login')
         ->seePageIs('dashboard')
         ->dontSee('Users');
    }
}

However using the model save method the tests pass:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class AuthTest extends TestCase
{
    //Run Migrations to Create Tables
    use DatabaseMigrations;

    public function setUp(){
      parent::setUp();
    }

    /**
     * Test Successful Login
     *
     * @return void
     */
    public function testGoodAdminLogin()
    {
      //Add the Test Admin User
      DB::table('users')->insert([
          'email' => 'admin@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => true
      ]);

      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->check('remember')
         ->press('Login')
         ->seePageIs('/dashboard')
         ->see('Users');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testFailedLogin()
    {
      //Add the Test Admin User
      DB::table('users')->insert([
          'email' => 'admin@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => true
      ]);

      $this->visit('/admin')
         ->type('admin@abc.co.za', 'email')
         ->type('secreT', 'password')
         ->press('Login')
         ->see('These credentials do not match our records.')
         ->seePageIs('/auth/login');
    }

    /**
     * Test Failed Login
     *
     * @return void
     */
    public function testNormalUserLogin()
    {
      //Add the Test User
      DB::table('users')->insert([
          'email' => 'company@abc.co.za',
          'password' => bcrypt('secreT5000'),
          'is_admin' => false
      ]);

      $this->visit('/admin')
         ->type('company@abc.co.za', 'email')
         ->type('secreT5000', 'password')
         ->press('Login')
         ->seePageIs('dashboard')
         ->dontSee('Users');
    }
}

jsdom 9.1+ does not set document.activeElement when focusing a node

I'm using jsdom with enzyme+mocha+chai to test the behavior of a React component. The component has a method to focus a DOM node (using the usual node.focus()) and I want to test the node is actually focused when it's called.

To know which node is focused, I compare document.activeElement to the node I expect to be focused.

However, after upgrading to jsdom 9.1+, document.activeElement seems always be HTMLBodyElement, even after calling the node's focus() method.

With jsdom 9.0 the tests run fine.

I read jsdom 9.1+ contains some changes related to the focus event, yet I couldn't understand how make document.activeElement behave as expected. Any help?

Mocking a non-abstract method of an abstract class

I am trying to unit-test a class that extends an abstract base class. Here are the "similar classes" for illustration purposes:

public class MyAbstractBaseClass {
  @Autowired
  private WaterFilter waterFilter;

  protected List<String> filterComponents(List<String> allComponents) {
    return waterFilter.filter(allComponents);
  }
}

public class MyDerivedClass extends MyAbstractBaseClass {
  public List<String> filterWater(List<String> allWaterComponents) {
    List<String> filteredComponents = this.filterComponents(allWaterComponents); //calls abstract class's filterComponets()
    filteredComponents.add("something-else");
    return filteredComponents;
  }
}

Here is the unit test I am trying:

    @RunWith(EasyMockRunner.class)
    public class MyDerivedClassTest {
        @TestSubject
        private MyDerivedClassTest SUT;

        @Before
        public void setup() {
           SUT = new MyDerivedClassTest();
        }

        @Test
        public void test filterWater_HappyCase() {
           //I want to mock my abstract class's filterComponents() method
           //I am trying this:
           EasyMock.expect(SUT.filterComponents(getDummyComponents())).andReturn(getSomeComponents());

          //What to replay here?
          //EasyMock.replay(...)

          List<String> actualResult = SUT.filterWater(getDummyComponents());

          //assert something
          //What to verify?
          //EasyMock.verify(...)
    }
}

When I run this test, I get java.lang.NullPointerException in MyAbstractBaseClass.filter(allComponents)

I understand that the autowired "waterFilter" is not getting initialized. But then, I just want to mock the "non-abstract" method of the abstract class in my unit test.

How should I go about this using EasyMock? Also, I don't know what to replay() and verify().

Example test of go templates fails with imported and not used: "testing"

As far as I can tell I'm following structure needed for 'go test' flawlessly. I don't see a discrepancy from tests I could run in other packages. 'go build' works fine. I'm getting

./HelloTemplate_test.go:3: imported and not used: "testing" ./HelloTemplate_test.go:5: undefined: Testing in Testing.T

What am I missing?

HelloTemplate.go

package templateprint

import "testing"

func TestRunTempl(t *Testing.T) {
    sweaters := Inventory{"wool", 17}
    tmpl := " items are made of "
    err := RunTempl(tmpl, sweaters)
    if err != nil {
        t.Error("Template failed ")
    }
}

HelloTemplate_test.go

package templateprint

import (
    "os"
    "text/template"
)

type Inventory struct {
    Material string
    Count    uint
}

func RunTempl(templ string, inv Inventory) error {
    tmpl, err := template.New("test").Parse(templ)
    if err != nil {
        return (err)
    }
    err = tmpl.Execute(os.Stdout, inv)
    if err != nil {
        return (err)
    }
    return nil
}

samedi 30 juillet 2016

Python 2.7: Error in unit-testing exception using mock library

I'm writing unit test for following method _make_post_request of APIClient class. But I'm having problem in writing unit test for this particular method. This method calls two more methods, out of which one raises an exception. I'm trying to mock both the methods and assert the exception is being raised.

I'm not able to understand how do I mock both methods in correct order, i.e. requests.post and _raise_exception at the same time. Also how can I verify that the exception was indeed raised in the test.

The case I'm testing is when response status_code is not 200 and hence, a APIRequestError exception is raised by _raise_exception method.

import requests

class APIClient:

    def _make_post_request(self, url, data=None, headers=None):
        try:
            resp = requests.post(url, data=data, headers=headers)
            if resp.status_code == 200:
                return resp
            else:
                self._raise_exception(resp)
        except requests.exceptions.ConnectionError:
            print("Connection Error")
        except requests.exceptions.Timeout:
            ......

    @staticmethod
    def _raise_exception(resp):
        status_code = resp.status_code
        error_code = resp.headers['Error-Code']
        error_msg = resp.headers['Error']
        raise APIRequestError(status_code, error_code, error_msg)

Here's what I have tried so far. But this test is failing.

import unittest
import mock

class APITest(unittest.TestCase):

    def setUp(self):
        api = APIClient()

    @mock.patch.object(APIClient, '_raise_exception')
    @mock.patch('APIClient.api.requests.post')
    def test_make_post_request_raise_exception(self, resp, exception):

        resp.return_value = mock.Mock(status_code=500, headers={
                                 'Error-Code': 128, 'Error':'Error'})

        e = APIRequestError(500, 128, 'Error')
        exception.side_effect = e

        req_respone = self.api._make_post_request(url='http://exmaple.com')


        exception_response = self.api._raise_exception(req_response)

        # NOW WHAT TO DO HERE?
        # self.assertRaises(??, ??)
        self.assertRaises(e, exception) # this results in error
        self.assertEqual('', exception_response) # this also results in error

Here's the traceback:

Traceback (most recent call last):
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File ".../api/tests/test_api.py", line 82, in test_make_post_request_raise_exception
req_respone = self.api._make_post_request(url='http://example.com')
File "api/apiclient/api.py", line 52, in _make_post_request
self._raise_exception(resp)
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__
return _mock_self._mock_call(*args, **kwargs)
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call
raise effect
APIRequestError

Can anyone explain me what could be the possible reason for this error? Which method call is possibly going wrong?

java.lang.ExceptionInInitializerError when mocking static method using EasyMock+PowerMock

I am trying to mock static method using EasyMock+PowerMock. If I dont mock the static method, then I get the exception java.lang.ExceptionInInitializerError but with a different stack trace which is purely due to my code files and the error is obvious. However, if I mock the static method using EasyMock+PowerMock, the line PowerMock.mockStaticNice(Classname.class) throws the same exception but with a different stack trace. The stack trace is:

 java.lang.ExceptionInInitializerError
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:348)
        at net.sf.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:386)
        at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219)
        at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
        at net.sf.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
        at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:175)
        at org.easymock.internal.MocksControl.createMock(MocksControl.java:114)
        at org.easymock.internal.MocksControl.createMock(MocksControl.java:88)
        at org.easymock.internal.MocksControl.createMock(MocksControl.java:79)
        at org.powermock.api.easymock.PowerMock.doCreateMock(PowerMock.java:2212)
        at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2163)
        at org.powermock.api.easymock.PowerMock.mockStaticNice(PowerMock.java:331)
        at PackageName(ClassName.java:125)
............................



The line 125 is PowerMock.mockStaticNice(Classname.class)

I have already tried this:
1) Mention class name containing static method in PrepareForTest({class1.class, class2.class, class3.class})
2) Mock static methods in @Before annotation.

I am stuck with this problem for the last 2 days. Kindly suggest solutions.

Function mocking in C?

I'm writing a unit-test to check some API calls. I am using check to test. My module is build with CMake (idk if it matters).

My test calls a function (which I need to test) and this function makes a call to another binary.

Simplified version of it looks like this.

/* unitTest.c */

#include "libraryAPI.h"
void letsMakeACall(void)
{
   ck_assert_eq(foo("water"), 0);
}

-- Module I am working on---
/*libraryAPI.c*/
#include "legacyLib.h"

void foo(const char *drink )    
{

    if (checkDrink(drink)!=0)
    {
       return 1;
    }else
    {
       return 0;
}


----LEGACY BINARY---
/*legacyLib.c*/

static const char* expected = "water";

void checkDrink(const char *drink)
{
    if(drink == expected)
     {
        /*There are also a dozen functions being called which depend on legacy module initialisation*/
        return 0;
     }else{
        return 1;
     }
}

I'd like to mock response from legacyLib, because otherwise it call dozens of functions and breaks. My initial idea was to add some ifdef conditions when tests are being run, but it is against guidelines. Because it is basically a call interception I don't know what it a best(or working) solution. What can I use to solve it?

thenReturn in not working

Unittestingclass

public class CollectionImplementationUnitTest {

CollectionImplementation col_Imp;

  public void setup() throws Exception {
  ....
  col_Imp = Mockito.spy(new CollectionImplementation());
  ....
  }

  private String mockHistoryFromStrgyTable(){
        String  value1  =   "myValue";
        return  value1;
  }

 @Test 
  public void testgetinfo (){
  ......
  Mockito.when(col_Imp.HistoryFromStrgyTable(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn(   mockHistoryFromStrgyTable());
  CollectionsAccount Info = col_Imp.AccountInfo("string1","string2","string3", new IdentityAcc(), TableLst)
  //sometestmethods and asserts
  }

}

CollectionImplementation.class

    public class CollectionImplementation{
      .....
      @override
      public CollectionsAccount AccountInfo(("string1","string2","string3", new IdentityAcc(), TableLst)){
      DetailsHelper helper = new (db2, "string",getmethod());
      return helper.AccountInfo("string1","string2", new IdentityAcc(), TableLst); 
      }
     public String HistoryFromStrgyTable(){
  //contains a call to the data base
  }
    }

DetailsHelper

public class DetailsHelper{
  public CollectionsAccount AccountInfo((String string1,String string2,String string3, new IdentityAcc(), TableLst)){
  ...
  String paymentdetails = HistoryFromStrgyTable();  
  }
   public String HistoryFromStrgyTable(){
   //contains a call to the data base
   }
}

When I try to mock the data for the method HistoryFromStrgyTable() it is actually making a call to HistoryFromStrgyTable() instead of getting from mockHistoryFromStrgyTable().

My test cases are failing at this line Mockito.when(col_Imp.HistoryFromStrgyTable(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn( mockHistoryFromStrgyTable());

Can anyone help me with this. I don't understand what's wrong. I also changed the method mockHistoryFromStrgyTable() from private to public since mockito cannot mock private methods.

Unit Testing Custom View Controllers in Swift Xcode 7

In my app project I have added a controller called "CalculatorViewController". I have set the target of "CalculatorViewController" to the project as well as the unit test project so I can access the CalculatorViewController inside the unit test project.

I have the following code in unit test:

class CalculatorViewControllerTests: XCTestCase {

    var viewController :CalculatorViewController!

    override func setUp() {
        super.setUp()

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

        self.viewController = storyboard.instantiateViewControllerWithIdentifier("CalculatorViewController") as! CalculatorViewController

    }

I get the following error:

Test Case '-[CalculatorAppTests.CalculatorViewControllerTests testExample]' started.
Could not cast value of type 'CalculatorApp.CalculatorViewController' (0x103144310) to 'CalculatorAppTests.CalculatorViewController' (0x10ee55b18).

Mocking child actor in Akka

I'm trying to write unit tests for my actor and am stuck on basic mocking. PriceAggregateActor is using akka persistence and I don't want to pass in all the conf for it and would like to mock it completely.

This is the actor that I want to test

object CommandPriceActor {
  def apply() = Props(classOf[CommandPriceActor], PriceAggregateActor())
}

class CommandPriceActor(priceAggregateActorProps: Props) extends Actor with ActorLogging {

  val priceAggregateActor = context.actorOf(priceAggregateActorProps, "priceAggregateActor")

So in my tests I'm trying to do something like:

class CommandPriceActorTest extends TestKit(ActorSystem("test-benefits",
  ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"] """))) with FlatSpecLike with Matchers
  with BeforeAndAfterAll with Eventually{

  class MockedChild extends Actor {
    def receive = {
      case _ => lala
    }
  }

  val probe = TestProbe()
  val commandPriceActor = TestActorRef(new CommandPriceActor(Props[MockedChild]))

I'm always getting:

Caused by: java.lang.IllegalArgumentException: no matching constructor found on class CommandPriceActorTest$MockedChild for arguments []

Why is it complaining about mockedChild? It shouldn't take any constructor arguments.

Untestable grails (2.5.4) service using @PostConstruct with Spock unit testing

I have a service that I wish to initialize with @PostConstuct, by fetching some configuration entries in Config.groovy.

I also wish to check that these entries were properly configured, and throw an exception so that I see that the application was misconfigured.

When writing a unit test for this service, I came to a dead end in Spock.

Spock apparently calls the @PostConstruct method, but only on the Shared Service instance, and then executes whatever instance methods you test, on the real instance under test.

This has a perverse side effect:

My init code either fails because I fail to add a setupSpec to initialize the shared instance, or it fails in the method under test, because the configuration has not actually been set on that instance.

Here's my service:

package issue

import org.codehaus.groovy.grails.commons.GrailsApplication

import javax.annotation.PostConstruct

class MyService {
    GrailsApplication grailsApplication
    String property

    @PostConstruct
    void init() {
        println "Initializing... ${this}"
        property = grailsApplication.config.myProperty

//Enabling this business sanity check make the service untestable under Spock, because to be able to run, we need to initialize the configuration
// of the shared instance - PostConstruct is only called on the shared instance for some reason.
// But the execution of the method under test will not have the initialized property, because the service being executed is not the shared instance
        if (property == "[:]") {
            throw new RuntimeException("This property cannot be empty")
        }
    }


    void doSomething() {
        println "Executing... ${this}"
        println(property.toLowerCase())
    }
}

Here's my first test:

package issue

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(MyService)
class MyServiceSpec extends Specification {

    def setup() {
        grailsApplication.config.myProperty = 'myValue'
    }

    void "It fails to initialize the service"() {
        expect:
        false // this is never executed
    }
}

Here's the second test:

package issue

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(MyService)
class MyServiceWithSharedInstanceInitializationSpec extends Specification {

    //Initializing the shared instance grailsApplication lets the @PostConstruct work, but will fail during method test
    //because the instance that was initialized is the shared instance
    def setupSpec() {
        grailsApplication.config.myProperty = 'myValue'
    }

    void "It fails to execute doSomething"() {
        when:
        service.doSomething()

        then:
        def e = thrown(NullPointerException)
        e.message == 'Cannot invoke method toLowerCase() on null object'
        service.property == null
    }
}

Is there a way to do this cleanly? Or do I have to let go my unit test and just make a (slower) integration test, to tiptoe around this weirdness?

You can see my full grails app here:

http://ift.tt/2ayO702

Using toString() for unit testing in Java

In a unit test, is it generally a good idea to test returned values according to the string their toString() returns?

For example, doing the following to make sure the expected list is returned:

 assertEquals(someExpression.toString() ,"[a, b, c]");

It seems to me that the considerations are as follows:

Pros: Saving time (constructing the actual expected value requires longer code).

Cons: The test depends on toString(), which is not formally defined in the doc, and thus can change in any future version.

How can I write automated tests for custom XCTest assertions?

I am developing a testing framework for iOS development. I'd also like for this testing framework to be well-tested. The problem is, I can't figure out how to write a test for my test target that asserts my framework is correctly causing failed tests. If I create a failed test, I have in turn, caused the test to fail (I know, it's confusing).

Consider an example. Part of my framework includes function to verify that a particular code snippet does not have any breaking constraints.

MTKAssertNoBrokenConstraints {
    // UI code that might break some constraints
}

I have tested this by hand to verify that when there are no broken constraints, the assertion passes, but when there are broken constraints, it correctly marks the test as failing.

But I need a way to verify that MTKAssertNoBrokenConstraints would mark a test as failing without actually marking the test for this itself as failing.

I have looked into creating a custom object that conforms to XCTestObservation, but so far I've only ended up with infinite recursion. I'm not sure whether this is the right path, or whether resolving the infinite recursion will actually get me where I need to be.

How to Handle Large Files in GitHub And Still Allow For AppVeyor Builds

GitHub has a limit on how large a file can be. I have an open source GitHub project that has a several 120mb files that will be required for unit testing... How do I store these files so that AppVeyor and other developers can access these files?

Ionic2/Angular2: Unit test service using SQLite

I'm currently developing an hybrid app using Ionic 2 (which is based on Angular 2). I'm using SQLite to store the data I need.

I've a service who reads and writes data into database.

I would like to unit test this service. I know how to run unit tests with Karma and Jasmine and inject services in it, but I'm a bit confused about the SQLite part.

I've written a DB service who connects to database and create the tables I need. I would like to test the functions firing the queries, test the format of data retrieved and some other functions using data retrieved from database.

So, should I mock functions executing the queries and test only the ones who process these data? Or is there a way to inject my DB service to get real queries executed?

BTW, as tests with Karma are ran into a browser, the Cordova SQLite plugin doesn't work so I need to mock SQLite somehow. I've read that we could use WebSQL instead to run the tests, but got no success so far.

My question isn't really about my particular code, it's more a general consideration about the best process to apply here.

Thanks for your inputs!

Junit: How to make every @Test methods isolated completely?

Example code:

public class Count {
    static int count;

    public static int add() {
       return ++count;
    } 
}

I want test1 and test2 run totally separately so that they both pass. How can I finish that? My IDE is Intellij IDEA.


public class CountTest {
    @Test
    public void test1() throws Exception {
        Count.add();
        assertEquals(1, Count.count);//pass.Now count=1
    }

    @Test
    public void test2() throws Exception {
        Count.add();
        assertEquals(1, Count.count);//error, now the count=2
    }
}

Assume the test1 runs before test2.

This is just a simplified code. In fact the code is more complex so I can't just make count=0 in @after method.

Test get crushed because of error " dangerouslyRenderMarkup " in react enzyme mocha testing

The full error text is Invariant Violation: dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure window and document are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering.

I have searched this issue but all solutions are connected with jsdom set up. My jsdom set up is here :

import jsdom from 'jsdom';
import jquery from 'jquery';
import TestUtils from 'react-addons-test-utils';
import ReactDOM from 'react-dom';
import chai, { expect } from 'chai';
import React from 'react';
import chaiJquery from 'chai-jquery';

// Set up testing environment to run like a browser in the command line
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = jquery(global.window);

// build 'renderComponent' helper that should render a given react class
function renderComponent(ComponentClass, props, state) {
   const componentInstance = TestUtils.renderIntoDocument(
      <ComponentClass {...props} />
   );

   return $(ReactDOM.findDOMNode(componentInstance)); // produces HTML
}

// Build helper for simulating events
$.fn.simulate = function(eventName, value) {
   if (value) {
      this.val(value);
   }
   TestUtils.Simulate[eventName](this[0]);
}

// Set up chai-jquery
chaiJquery(chai, chai.util, $);

export { renderComponent, expect };

p.s. i don't use renderComponent function. I use enzyme mount instead

here is example of my test code

'use strict';
import React from 'react';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import chai, { expect } from 'chai';
import Profile_Store from '../profile.store';
import Signup from '../components/signup.component';

describe('__Signup__', ()=> {
   let signup_stub, spySubmit, spyCloseHint, wrap, context, email, pssword, passwordConfirm, submit, form_hint, input__hint;

   beforeEach(() => {
      spySubmit = sinon.spy(Signup.prototype, 'handleSubmit');
      signup_stub = sinon.stub(Profile_Store.prototype, 'signup');
      spyCloseHint = sinon.spy(Profile_Store.prototype, 'clearErrorMessage');
      context = {
         profile: new Profile_Store()
      };
      wrap = mount(<Signup  />, {context});
      email = wrap.find('input[type="email"]');
      pssword = wrap.find('input[type="password"]');
      submit = wrap.find('button[type="submit"]');
      input__hint = wrap.find('.input__hint');
      form_hint = wrap.find('.form__hint');
   });
   afterEach(() => {
      spySubmit.restore();
      spyCloseHint.restore();
      signup_stub.restore();
   });

   it("contains all inputs, button and validation hints", function() {
      expect(email).to.have.length(1);
      expect(pssword).to.have.length(2);
      expect(submit).to.have.length(1);
      expect(form_hint).to.have.length(1);
      expect(input__hint).to.have.length(3);
   });

   it("validation messages are hidden by default", function() {
      expect(form_hint.hasClass('hidden')).to.equal(true);
      input__hint.forEach((hint) => {
         expect(hint.hasClass('hidden')).to.equal(true);
      });
   });

   it("validation messages are visible if error", function() {
      context = {profile: new Profile_Store()};
      wrap = mount(<Signup  />, {context});
      wrap.context().profile.errorMessage = 'registration failed';
      expect(wrap.find('.form__hint').hasClass('visible')).to.equal(true);
      expect(wrap.find('.form__hint > span').at(0).text()).to.equal('registration failed');
   });

   it("validation messages are hidden while click close hint", function() {
      context.profile.errorMessage = 'registration failed';
      wrap = shallow(<Signup  />, {context});
      wrap.find('.form__closeHint').simulate('click');
      expect(context.profile.errorMessage).to.equal('');
      wrap = shallow(<Signup  />, {context});
      expect(wrap.find('.form__hint').hasClass('visible')).to.equal(false);
      sinon.assert.calledOnce(spyCloseHint);
   });

   it('form work correctly', () => {
      const event = {target: {value: 'cats'}};
      wrap.ref('email').simulate('change', event);
      wrap.simulate('submit',  { preventDefault() {} });
      chai.assert.equal(spySubmit.callCount, 1);
      sinon.assert.calledOnce(signup_stub);
   });

   it('don\'t handle Submit with empty values', () => {
      wrap.setState({
         validEmail: null,
         validPassword: null,
         validPasswordConfirm: false
      });
      wrap.simulate('submit',  { preventDefault() {} });
      sinon.assert.notCalled(signup_stub);
   });
});

Running MsTest.exe from Batch script

I am trying to automate running a C# solution's unit tests from a batch script.

My script is working fine, until it comes to actually calling MsTest.exe with the /testcontainer and /test flags in the MsTest call.

Batch script below:

@echo OFF
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

echo Detecting System specification...
echo.

reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT

set programFilesPath=xyz

if %OS%==32BIT (
    echo 32bit operating system detected.
    echo.
    set programFilesPath=%ProgramFiles%\Microsoft Visual Studio
) ELSE (
    echo 64bit operating system detected.
    echo.
    set programFilesPath=%ProgramFiles(x86)%\Microsoft Visual Studio
)

echo Checking for Visual Studio installations...
echo.

set /a highestVSVersion=54
set /a installationPath=xyz
set /a vsCount=0

for /d %%a in ("%programFilesPath%"*) do (

    rem echo "%%a"
    rem set installationPath=%%a
    rem echo !installationPath!
    rem echo !vsCount!

    for /f "tokens=5" %%g in ("%%a") do (
        set tempStr=%%g
        set tempStr=!tempStr:~0,2!

        if not "!tempStr!"=="!tempStr:.=!" (
            set tempStr=!tempStr:.=!
        )

        set tempTwo=0
        set tempTwo=!tempStr!

        if !vsCount! EQU 0 (
            set highestVSVersion=!tempTwo!
        ) else (
            if !tempTwo! GTR !highestVSVersion! (
                set highestVSVersion=!tempTwo!
            )
        )
    )

    set /a vsCount=!vsCount!+1
)

if !vsCount! EQU 0 (
    echo No Visual Studio installation found. Please install visual studio to run unit tests.   
    echo.
) else (

    if !highestVSVersion! GTR 9 (
        set highestVSVersion=!highestVSVersion!.0
    )

    echo Visual Studio !highestVSVersion! found.
    echo.
    echo Verifiying MsTest.exe location for Visual Studio !highestVSVersion!...
    echo.
    set fullPath=!programFilesPath! !highestVSVersion!\Common7\IDE\MsTest.exe

    if exist !fullPath! (
        echo MsTest.exe found at: !fullPath!
        echo.
        echo Running all tests in src\DictionaryDash.Testing
        set testContainerArg=src\DictionaryDash.Testing\bin\Release\DictionaryDash.Testing.dll

        call "!fullPath!" /testcontainer: !testContainerArg!
    )
)

pause

Where I am having trouble is the last call line. I get the following output in the command window:

Detecting System specification...

32bit operating system detected.

Checking for Visual Studio installations...

Visual Studio 12.0 found.

Verifiying MsTest.exe location for Visual Studio 12.0...

MsTest.exe found at: C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\M
sTest.exe

Running all tests in src\DictionaryDash.Testing

Microsoft (R) Test Execution Command Line Tool Version 12.0.21005.1

Copyright (c) Microsoft Corporation. All rights reserved.

Invalid switch "src\dictionarydash.testing\bin\release\dictionarydash.testing.dl
l".

Please specify a parameter for the /testcontainer switch.

For switch syntax, type "MSTest /help"

Press any key to continue . . .

It is successfully finding MsTest.exe but when it comes to passing an argument to the /testcontainer switch that it fails. The script file is located in the root of the project directory at the same level as the "src" directory.

Thanks!

Specs2 tests fails under terminal but work under Intellij IDEA

I'm working on Play 2.5 application in Scala and I'm using Specs2 for testing. Here is my test class:

class Entity1ServiceSpec extends Specification with Mockito {
  private val entity1Repository = mock[Entity1Repository]
  private val entity1Service: Entity1Service = new Entity1ServiceImpl(entity1Repository)

  "Create AddedMessage" should {
    "return true" in {
      running(FakeAppBuilder.buildFakeApp) {
        entity1Repository.create(0, "911", "01", 20) returns true
        val result = entity1Service.create(0, "911", "01", 20)
        there was one(entity1Repository).create(0, "911", "01", 20)
        result shouldEqual true
      }
    }

    "return false" in {
      running(FakeAppBuilder.buildFakeApp) {
        entity1Repository.create(1, "911", "01", 10) returns false
        val result = entity1Service.create(1, "911", "01", 10)
        there was one(entity1Repository).create(1, "911", "01", 10)
        result shouldEqual false
      }
    }
  }

}

When I run the tests under Intellij Idea, everything works well but when I run it under the terminal using sbt test it fails with the following stacktrace:

[error] cannot create an instance for class services.Entity1ServiceSpec
[error]   caused by org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
[error] Misplaced argument matcher detected here:
[error] 
[error] -> at org.specs2.mock.mockito.MockitoMatchers$class.any(MockitoMatchers.scala:45)

Can someone help me to figure out what am I doing wrong?

How can I run my performance tests more than ten times?

By default Xcodes performance tests are run ten times and my result is the average of those ten tests. The problem is this averaged result varies considerably each time I run it so I usually run the test five times to get a better converged result. It is a little bit tedious and time consuming, is there a way of configuring either XCode or the unit test itself to run more than ten times?

enter image description here

IBM JSON4J ClassNotFound when running unit test

I am developing a basic servlet deployed on WebSphere Liberty. This servlet uses a custom class I wrote to perform its business logic.

I tried to write some unit tests for this custom class which I can run using maven. But when I launch maven test, some tests fail with the following exception:

java.lang.NoClassDefFoundError: com/ibm/json/java/internal/SerializerVerbose
at com.ibm.utils.JMAuthorizationModule.processPostRequest(JMAuthorizationModule.java:78)
at com.ibm.test.JMAuthorizationModuleTest.shouldNotAcceptToCreateASkillForADifferentUser(JMAuthorizationModuleTest.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.ClassNotFoundException: com.ibm.json.java.internal.SerializerVerbose
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 32 more

The class that I intend to test uses the IBM Library JSON4J. The class can run without any problem when my servlet is deployed inside the Liberty runtime, but apparently the JSON4J is not found by maven when the tests are run.

Could you please explain what I should configure so that the ClassNotFound is not thrown when running my tests?

I also attach my pom.xml in case it may help:

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

<repositories>
    <repository>
        <id>maven online</id>
        <name>maven repository</name>
        <url>http://ift.tt/1Suicfc;
    </repository>
    <repository>
        <id>liberty maven online</id>
        <name>liberty maven repository</name>
        <url>http://ift.tt/1rmldQx;
    </repository>
</repositories>

<modelVersion>4.0.0</modelVersion>
<groupId>com.ibm.jm.tests</groupId>
<artifactId>TestSecurityGateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Test</name>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-servlet_3.0_spec</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.ibm.tools.target</groupId>
        <artifactId>was-liberty</artifactId>
        <version>LATEST</version>
        <type>pom</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-servlet_3.0_spec</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.9.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <warName>JMTestApp</warName>
                    <outputDirectory>bluemix/apps</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Thanks

List appending not working in python 3

I have a testing environment in the following way

request1 = b"""INVITE sip:foo SIP/2.0
From: mo
To: joe
Content-Length: 4

1234

lalalal""".replace(b"\n", b"\r\n")

class MessageParsingTests(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.parser = sip.MessagesParser(self.l.append)

    def feedMessage(self, message):
        self.parser.dataReceived(message)
        self.parser.dataDone()

    def testSimple(self):
        l = self.l
        self.feedMessage(request1)
        self.assertEqual(len(l), 1)

Now this test works fine on Python 2 but fails on Python 3. with the following traceback

[FAIL]
Traceback (most recent call last):
 File "/home/ac/twisted-8673/twisted/test/test_sip.py", line 126, in     testSimple
self.assertEqual(len(l), 1)
  File "/home/ac/twisted-8673/twisted/trial/_synctest.py", line 425, in assertEqual
  super(_Assertions, self).assertEqual(first, second, msg)
  File "/usr/lib/python3.5/unittest/case.py", line 820, in assertEqual
assertion_func(first, second, msg=msg)
  File "/usr/lib/python3.5/unittest/case.py", line 813, in _baseAssertEqual
raise self.failureException(msg)
twisted.trial.unittest.FailTest: 0 != 1

twisted.test.test_sip.MessageParsingTests.testSimple

I don't understand where the list appending occurs in this code. and what exactly happens in this line self.parser = sip.MessagesParser(self.l.append). I can see that call to feedMessage method causes list appending in Python2 but didn't understand that either.

Any help is appreciated

vendredi 29 juillet 2016

mockery not able to register substitute

I have a problem registering substitutes with mockery. My usecase is that I want to substitute react-native-router-flux with my own. So I created a file rn-router-mock.js which resides in a path something like ./../test/mock/rn-router-mock relative to my test file.

My code mockery.registerSubstitute('react-native-router-flux', './../test/mock/rn-router-mock') fails with an error

Error: Cannot find module './../../test/mock/rn-router-mock'
    at Function.Module._resolveFilename (module.js:325:15)
    at Module._load (module.js:276:25)

However note that I am able to require('./../test/mock/rn-router-mock') from the same test code.

And the same works when I give the full path to the mock module.

Any help will be greatly appreciated.

Pythonic approach to testing properties?

I've run into an issue writing unit tests for class attributes with the @property decorator. I am using the excellent py.test package for testing and would definitely prefer sticking with it because it's easy to set up fixtures. The code for which I'm writing unit tests looks something like this:

    class Foo(object):

        def __init__(self, fizz, buzz, (and many more...)):
            self.fizz = fizz
            self.buzz = buzz
            self.is_fizzing = #some function of fizz
            self.is_fizz_and_buzz = fizz and buzz
            ...

        @property
        def is_bar(self):
            return self.is_fizz_and_buzz and self.buzz > 5

        @property
        def foo_bar(self):
            # Note that this property uses the property above
            return self.is_bar + self.fizz

        # Long list of properties that call each other

The problem occurs when writing a unit test for a property which uses multiple other properties sometimes in long chains of up to four properties. For each unit test, I need to determine which inputs I need to set up and, even worse, it may be the case that those inputs are irrelevant for testing the functionality of that particular method. As a result, I end up testing many more cases than necessary for some of these "properties."

My intuition tells me that if these were actually "properties" they shouldn't have such long, involved calculations that need to be tested. Perhaps it would be better to separate out the actual methods (making them class methods) and write new properties which call these class methods.

Another issue with the current code--correct me if I'm wrong--is that every time a property is called (and most properties are called a lot) the attribute is recalculated. This seems terribly inefficient and could be fixed like this with new properties.

Does it even make sense to test properties? In other words, should an attribute itself be calculated in a property or should it only be set? Rewriting the code as I described above seems so unpythonic. Why even have properties in the first place? If properties are supposed to be so simple to not require testing, why not just define the attribute in the init?

Sorry if these are silly questions. I'm still fairly new to python.

Unit Test for controller in AngularJs Failed

Here is my controller:

'use strict';
angular.module('pulseOneApp')
  .config(function ($stateProvider) {
    $stateProvider.state('about', {
      url: '/about',
      views: {
        'content': {
          templateUrl: 'components/version/about.html',
          controller: 'AboutController'
        }
      },
      authNotRequired: true
    });
  })

  .controller('AboutController', ['$scope', '$state', 'session', '$pulseOneProps', '$filter', 'propertiesServices', function ($scope, $state, session, $pulseOneProps, $filter, propertiesServices) {

    /**
     * @function  getServerVersion
     * @description gets the serverVersion from $pulseOneProps if exist, else makes a REST Api call using propertiesServices.
     * @returns string
     */
    var getServerVersion = function () {
      var systemProperties,serverVersion;
      if ((angular.isDefined($pulseOneProps))  && $pulseOneProps !== null) {
        systemProperties = $pulseOneProps.getProperties();
        if(systemProperties) {
          return $filter('filter')(systemProperties, {name: 'server_version'})[0].value;
        }
        else{
          //when the session exist and not able to retrieve $pulseOneProps then do REST Api call and update the systemProperties
          session.validateSession().then(function() {
            propertiesServices.getPulseOneProperties().then(function (systemProperties) {
              serverVersion=$filter('filter')(systemProperties, {name: 'server_version'})[0].value;
              // This will update the UI when serverVersion is available
              $scope.serverVersion = (serverVersion) ? serverVersion: false;
            });
          });
        }
      }
      return null; // if none of the above cases are valid then don't display the server version.
    };

    var serverVersion=getServerVersion();
    $scope.serverVersion = (serverVersion) ? serverVersion: false;

    $scope.goTo = function() {
      session.validateSession().then(function() {
        $state.go('app.dashboard');
      })
      .catch(function() {
        $state.go('login');
      });
    };
  }]);

and Here is my Unit Test for this controller to make sure the function goTo is the function:

'use strict';

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

  // load the controller's module
  beforeEach(module('ui.router'));
  beforeEach(module('ps.authentication.services'));
  beforeEach(module('ps.version'));
  beforeEach(module('pulseOneApp'));
  beforeEach(module('ps.components.properties'));


  var scope, AboutController;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($rootScope, _$controller_) {
    scope = $rootScope.$new();
    AboutController = _$controller_('AboutController', {
      $scope: scope
     });
    scope.$digest();
  }));

  it('should find to goTo function', function () {
    expect(typeof scope.goTo).toBe('function');
  });
});

The unit test is failed and I don't know what was wrong with this unit test. Any suggestion what was the issue here. Thanks in advance -k

Improving code coverage for the @builder in Lombok

Is there a way to test the @Builder annotation used in Lombok? I use the pattern to build my classes and my code coverage keeps dropping as I use it more.

Any ideas on this?

sails.js socket.io unit test

I'm developing an app using Sails + Angular and I want to create Unittest for my Angular controllers.

In my Angular controller I have this code:

io.socket.on('user',function(obj) {
   ...
}

How do I mock socket.io server to test the above code?

I'm using Jasmine/Karma to write and run my Angular test.

Thanks, TD

Open Access DB using NAnt build script

I am trying to open an Access DB in a Unit Test.

The following code works fine while running the test in Visual Studio Test Explorer, but fails while using NAnt build script.

    public static void CreateAccessDBConnection()
    {
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data"
                    + @" Source=~\..\..\..\..\MeisTestingData.accdb";

        conn = new System.Data.OleDb.OleDbConnection(connectionString);

        conn.Open(); //This call is failing --> System.Runtime.InteropServices.SEHException : External component has thrown an exception
    }

<copy file="${build.dir}/${app.name}.MVC.QA.dll-results.xml" tofile="${build.dir}/MEIS-Unit-Tests-Result.xml" overwrite="true" />

How to unit test method with if else and no return conditions

I have a method with following code:

public void myMethod() {
    if (condition1) {
        doSomething1();
        if (condition2) {
            doSomething2();
        } else {
            doSomething3();
        }
    }
 }

Now doSomething1, doSomething2, doSomething3 are void methods. How to unit-test myMethod ? eg: if condition1 is satisfied check if doSomething1 was called.

Is there something we can do to refactor this to make easily testable ?

Testing request and response messages format with IBM MQ

I have over 1000 sample messages.Simply, I send this message to MQ and receive the response, one by one.These response should be validated against to the request messages.What would be the most effective way I can do the testing using JBehave , Junit and java?. (One message represents a particular scenario).

Mockito Unit Test Case call is Ambiguous (Need to get it to not be ambiguous)

How should I write the following Mockito Matchers so that the call is not ambiguous?

The actual function call I am trying to mock in my code is:

//Variables
String url = http://theServer:8080/oath2-v1/token;
HttpEntity<String> request = new HttpEntity<String>("name=value",headers);

//Method call I am trying to mock using Mockito
response=cmsRestTemplate.exchange(url, HttpMethod.POST, request, DdsOAuthToken.class);

Below is a snippet from my Unit Test case. It contains the following mocked call emulating the above call, but unfortunately the compiler finds it ambiguous and won't compile.

//From the Unit Test...
when(restTemplate.exchange(
    Matchers.anyString(),
    Matchers.any(HttpMethod.class),
    Matchers.any(HttpEntity.class),
    Matchers.<Class<DdsOAuthToken>>any(),
    Matchers.anyVararg()).thenReturn(response));

The error I get is as follows:

The method exchange(String, HttpMethod, HttpEntity<?>, Class<DdsOAuthToken>, Object[]) is ambiguous for the type RestTemplate

This is a Spring RestTemplate api call. Specifically the 2 api calls it finds ambiguous are the 2 following calls:

1. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)

2. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)

I am trying to mock #1 above. But the Java Compiler can't tell if I'm trying to call #1 or #2. Exactly how should I write the Mockito matchers so that it knows I want #1 above and not #2?

How to make this function testable?

I have a function responsible for collecting a bunch of configurations and making a bigger configuration out of all these parts. So it's basically:

let applyUpdate updateData currentState =
    if not (someConditionAbout updateData) then
        log (SomeError)

    let this = getThis updateData currentState.Thingy
    let that = getThat updateData currentState.Thingy
    let andThat = createThatThing that this updateData

    // blablablablablabla

    { currentState with
        This = this
        That = that
        AndThat = andThat
        // etc. }

I currently have unit tests for getThis, getThat, createThatThing, but not for applyUpdate. In an object-oriented style, these would be passed via an interface through dependency injection. In a functional style I'm unsure as to how to proceed:

// This is the function called by tests
let applyUpdateTestable getThisFn getThatFn createThatThingfn etc updateData currentState =
    if not (someConditionAbout updateData) then
        log (SomeError)

    let this = getThisFn updateData currentState.Thingy
    // etc

    { currentState with
        This = this
        // etc. }

// This is the function that is actually called by client code
let applyUpdate = applyUpdateTestable getThis getThat etc

This seems the functional equivalent of Bastard Injection, but beyond that I'm mainly concerned with:

  • now my code is harder to follow because you can't just F12 (Go to Definition) into functions; this problem also exists with dependency injection but is mitigated by tooling (i.e. Resharper Go To Implementation).
  • The function I'm testing isn't technically the one called by production code (there could be errors in the mapping)
  • I don't even see a good name for that "Testable" version of the function
  • I'm polluting the module with duplicate definitions of everything

How do deal with these problems in functional programming?

Unit Testing of Angular 2 Component using Jasmine

I am trying to unit test the Angular 2 Component using Jasmine. My Component is as follows

import { Component } from '@angular/core';
import {Employee} from './Employee'; 
@Component({
    selector: 'emp-data',
    templateUrl: './app/app.html'
})
export class EmployeeComponent {
    emp:Employee;
    private name: string = 'John';
    constructor() {
        this.emp  =new Employee();
     }

     getTax():number{
         console.log('sal' + this.emp.salary + ' desig ' + this.emp.designation);
         
         if(this.emp.designation=='Manager'){
             this.emp.tax = this.emp.salary*0.3;
         }
         if(this.emp.designation=='Lead'){
             this.emp.tax = this.emp.salary*0.25;
         }
         console.log("Tax " + this.emp.tax);
         
         return  this.emp.tax;
     }
     printMessage():string{
            return `Hello ${this.name}`;
     };


}

The Spec file is as follows

import  {EmployeeComponent} from './appcomponent';
describe('EmployeeComponent',()=>{
    beforeEach(()=>{
        this.app = new EmployeeComponent();
    });
    it('should have name property', function() {
    expect(this.app.name).toBe('Mahesh');
  });

  it('should say hello with name property', function() {
    expect(this.app.printMessage()).toBe('Hello Mahesh');
  });
});    
The Tester.html file is as follows
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title>Ng App Unit Tests</title>
  <link rel="stylesheet" href="../node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
     
 <script src="../node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="../node_modules/systemjs/dist/system-polyfills.js"></script>

    <script src="../node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="../node_modules/reflect-metadata/Reflect.js"></script>
    <script src="../node_modules/zone.js/dist/zone.js"></script>
<script src="../node_modules/@angular/core/testing/testing.js"></script>
 <script src="systemjs.config.js"></script>
  <script src="../app/appcomponent.js"></script>
<script src="../app/component.spec.js"></script>
</head>
 <body>
  <script src="node_modules/systemjs/dist/system.src.js"></script>

  <script>
     System.config({
      packages: {
        'app': {defaultExtension: 'js'}
      }
    });

  
    System.import('app/component.spec')
      .then(window.onload)
      .catch(console.error.bind(console));
  </script>
</body>

</html>

The Package.json is as follows

{
  "name": "ng2-component-testing",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrently \"tsc -w\" \"node server.js\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install",
    "testLite": "live-server --open=unit-tests.html",
    "lite-server-test": "lite-server --config=liteserver-test-config.json",
    "test": "tsc && concurrently \"npm run tsc:w\" \"npm run lite-server-test\" "

  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.1",
    "@angular/compiler": "2.0.0-rc.1",
    "@angular/core": "2.0.0-rc.1",
    "@angular/http": "2.0.0-rc.1",
    "@angular/platform-browser": "2.0.0-rc.1",
    "@angular/platform-browser-dynamic": "2.0.0-rc.1",
    "@angular/router": "3.0.0-alpha.3",
    "bootstrap": "^3.3.6",
    "es6-shim": "^0.35.1",
    "jasmine-core": "~2.4.1",
    "koa": "^1.2.0",
    "koa-static": "^2.0.0",
    "livereload": "^0.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "^0.19.24",
    "zone.js": "0.6.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "jasmine-core": "2.4.1",
    "lite-server": "^2.1.0",
    "node-gyp": "^3.3.1",
    "typescript": "^1.8.7",
    "typings": "^0.7.5"
  }
}

When I run the test, the following result is displayed enter image description here

The following error messages are displayed in Console of the browser

enter image description here

I have tries various solutions on Stackoverflow but not successful in it.

So can anybody help me on this? Thanks in advance.

Jenkins iOS build - FATAL: Log statements out of sync: current test case was null

I have a jenkins build server that is configured to build my iOS project. Recently the build times have greatly increased, going from around 2 min/build to 10 min/build. While watching the console output, I can see that the build keeps getting hung up after the error message:

FATAL: Log statements out of sync: current test case was null

It takes probably a minute for the build to continue running. These messages seem to be occurring after a suit of test cases are run (XCTest framework).

Has anyone seen this console log before? Any help would be greatly appreciated, as I cant seem to find much information online.

My Jenkins Xcode plugin is version 1.4.9, and JUnit plugin is 1.9.

Unit testing Backbone Views

Unit testing with mocha,sinon,chai , jsdom.

When I unit test Backbone Views, I get the error $el.toolTip is not a function.

toolTip is actually defined in bootstrap.js file.

I am not sure whether I have to load bootstrap in nodejs env. (since the tests run in nodejs).

How to load the bootstrap file in nodejs env or in jsdom?

Can someone help here?

Redux Unit Test - reducers and action creators

I'm recently learning Redux and writing Unit Test as part of TDD process using Jest

Im writing test for action creators and reducers. But i'm struggling with: can I make use of action creators in the reducers test?

import * as types from './../../constants/auth';
import * as actions from './../../actions/auth';
import reducer, {initialState} from './../auth';

can I do this

it('it should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, actions.loginPending())
    ).toEqual(expectedState)
});

instead of this?

it('it should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, {type: types.LOGIN_PENDING})
    ).toEqual(expectedState)
});

I came to this doubt because the official documentation use hard coded action in the reducers test:

expect(
  reducer([], {
    type: types.ADD_TODO,
    text: 'Run the tests'
  })
).toEqual([{
      text: 'Run the tests',
      completed: false,
      id: 0
}])

I guess using hard coded actions is the best practice isn't?

Where is the xml file generated saved after running xmlrunner?

I have my unittest suite and this piece of code. Where is the xml file saved?

 if __name__ == '__main__':
     unittest.main(verbosity=2, testRunner=xmlrunner.XMLTestRunner(filename='test-reports.xml'))

Thanks in advance

Hot verify method arguments with Mockito when they change after method invocation

I have following test code. The code here might look a little bit strange but I took it from a bigger application and removed all unimportant parts.

interface Checker {

    public void check(Set set);
}

public void methodToTest(Checker checker, Set things){
    checker.check(things);
    things.add("3");      
}


@Test
public void test() {

    Checker checker = mock(Checker.class);
    Set argSet = Sets.newHashSet("1", "2");
    Set exSet = Sets.newHashSet("1", "2");

    methodToTest(checker, argSet);

    verify(checker).check(exSet);
}

Comparison Failure: Expected :checker.check([1, 2]); Actual :checker.check([1, 2, 3]);

After debugging I found out that Mockito stores the argument of the method call by reference. So it points to the argSet which gets changed before verifying.

How can I solve that issue. Is there a way to somehow tell mockito to store the argument state at the point of method invocation?

How to interpret and run the following ant command?

I am new to nodeJS and Jake but in my company they are using it to run unit tests.This is how they are running unit tests through ant

    <exec executable="cmd" dir="${nodeJsTests.basedir}/../nodejs/">
        <arg value="/C"/>
        <arg value="start cmd /C &quot;npm install &amp; .\node_modules\.bin\jake local dir=${basedir} --trace &amp; pause&quot;" />
    </exec>

From what I understood is they are doing the following things in this piece of code, do correct me if I am wrong

  1. Going to nodejs driectory.
  2. Installing jake at a particular location (.\node_modules.bin\jake)
  3. Run unit tests

I want to achieve the same(run the tests), without using ant.I think I am able to do first two steps but stuck in the third step.I tried running command - Jake local from various directories but no success

If anyone can help me on this?

What is the most idiomatic way in Go to test code which has dependency on structure with big amount of methods?

Lets say I have a UserRepository struct which incapsulates logic for interacting with a database. This struct has a set of methods like:

  • findAll()
  • findById()
  • findByName()
  • save()
  • and so on....

There is another struct (let's call it UserService for instance) which depends on UserRepository struct.

To test UserService I need to mock functionality of UserRepository. The only way I know to do this is to provide the interface for UserRepository and make UserService be dependent on it instead of UserRepository struct. It will allow to create a mocked implementation of interface and set it as dependency of UserService in the test.

What is the most idiomatic way to do it?

1) If UserService depends only on 1 UserRepository's method (let's say findAll) - should I still define an interface which will have all repository methods or it's better to define a separate interface for this method only and use it as a dependency of UserService? If so, what is the best name for it (interface)? If another struct will depend on findAll() and findById() methods should I again create another interface?

2) Where is a best place to store mocks for these interfaces? Is it possible to reuse them? Or for tests of different structs I will need redefine the mocks?

P.S. as for me unit tests is a very important part of the project. I would like to make them as readable as possible avoiding boilerplate code and focusing on their logic. So creating several mock implementations for same interfaces in different test files looks for me a bad option since it makes test code less readable.

How to write a proper Junit test for this Rest client controller

I know that this is very bold question, but maybe someone can at least lead on the correct way....

  @RequestMapping(value = "/check", method = RequestMethod.POST)
        public String checkUser(@ModelAttribute(value="userl") User userl)  {

        final String uri = new String(URL + "login");
        //make request to REST service and redirect to users page
         try{   
             RestTemplate restTemplate = new RestTemplate();
             ResponseEntity<User> responseEntity =  restTemplate.postForEntity(uri,userl,User.class);
             headers = responseEntity.getHeaders();
             setHeader(headers);
             User currentUser = responseEntity.getBody();
             System.out.println(currentUser.toString());
             logedUser.setUserType(currentUser.getUserType());

                    return "redirect:/users";       
            }
         //if request failed, redirect to login page
         catch(Exception e){
             e.getMessage();
             return "redirect:/";
         }                                  
    }

jasmine parameterized unit test

Okay as a C# NUnit guy this might be odd.

But does jasmine allow parameterized unit test?

I am not sure if it goes against the "declare" and "it" to make things readable to non programmers.

I have seen some third party plug ins but they are kind of old, not sure if it has been added to jasmine. If I am ment to use a plug in

How to mock TemporaryFile moveTo() method?

I'm trying to create a test case for the controller below but I'm encountering some issues that I believe to be related to mocking methods correctly.

Issue:

Every time my test runs through this line:

file.ref.moveTo(new File(s"${configuration.uploadFileLocation}/$filename").getCanonicalFile,true)

it throws the following error:

Error:

[info] - run test *** FAILED ***
[info]   java.lang.NullPointerException:
[info]   at java.nio.file.Files.provider(Files.java:97)
[info]   at java.nio.file.Files.move(Files.java:1392)
[info]   at play.api.libs.Files$TemporaryFile.moveTo(Files.scala:100)

Controller:

def run = Action.async(parse.multipartFormData) { implicit request =>
  request.body.file("file").map { file =>
  import java.io.File
  val filename = randomFileName
  val contentType = file.contentType
    if(contentType == Some("text/csv")) {
     file.ref.moveTo(new File(s"${configuration.uploadFileLocation}/$filename").getCanonicalFile,true)
    val result = addressApiClient.multipleMatch(filename)
    result.map(a => Ok(views.html.multipleMatch(Some(a), None, Some(filename))))
  }else {
    Future.successful(Ok(views.html.multipleMatch(None, Some("add message..."),None)))
  }
}.getOrElse {
  Future.successful(Ok(views.html.multipleMatch(None, Some("add message..."),None)))
}
}

Test case:

test("run() test") {
 val mockMessageApi    = mock(classOf[MessagesApi])
 val mockApiClient     = mock(classOf[AddressApiClient])
 val mockConfiguration = mock(classOf[Configuration])
 val mockFile          = mock(classOf[File])

 val buildFakeRequest =  FakeRequest(POST, "", FakeHeaders(), {
  val tempFile =  new TemporaryFile(mockFile)
  val filePart = FilePart("file", "test.file", Some("text/csv"), tempFile)
  MultipartFormData(Map(), List(filePart), List())
}
)

val controller = new MultipleMatch(mockApiClient, mockMessageApi, mockConfiguration)
val response   = controller.run()(buildFakeRequest)
}

Question:

How can I effectively mock the ref and the moveTo method? Please explain what is causing this to happen so I don't fall on the same issue again in the future. Many thanks