dimanche 31 janvier 2016

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

I am trying on unit test for login using karma and jasmine. I got the following error when I test my code using karma start unit-tests.conf.js.

PhantomJS 1.9.8 (Mac OS X 0.0.0) LoginController doLoginAction should call login method on UserService FAILED

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

Here I am including my login.controller.tests.js page.

describe('LoginController', function() {

var scope, controller, userServiceMock, stateMock;

beforeEach(module('user.controllers'));

beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    controller = $controller('LoginController',{
        $scope: scope,
        $state: stateMock,
        UserService: userServiceMock
    });
}));

beforeEach(function() {
    scope.doLoginAction = jasmine.createSpy('doLoginAction')
});

describe('doLoginAction',function(){
    it('should call odLoginAction method on LoginController', function(){
        scope.doLoginAction();
    });

    it('should call login method on UserService', function(){            
        spyOn(userServiceMock,'login');
        expect(userServiceMock.login).toHaveBeenCalledWith({username:'riju@gmail.com',password:'riju'});

    });
});

});

doLoginAction function in my controller page.

$scope.doLoginAction = function () {
            UserService.login($scope.creds.username, $scope.creds.password)
                .then(function (_response) {

                    alert("login success " + _response.attributes.username);

                    // transition to next state
                    $state.go('tab.list');

                }, function (_error) {
                    alert("error logging in " + _error.message);
                })
        };

What I am doing wrong, please help me. thanks

How to have initialization method for test methods in separate classes?

Currently, I have a whole bunch of test methods that rely on various assortments of the same testing infrastructure, which is quite costly to create. As a result, I built a test class with an initialization method in which the common infrastructure for the testing is instantiated, like so:

public class CostEngineTests
{
    // some private methods A to F used to build infrastructure 

    [TestInitialize]
    public void Initialize()
    {
         // build a bunch of infrastructure here with A to F
    }

    [TestMethod]
    public void CostEngine1()
    {
        // put my engine-specific infrastructure creation and tests here
    }

    // about 20 more test methods to the same effect
}

But I've been told that this class is simply too big, and each method should be separated into its own class (in a separate file). My first thought would be to just create whatever infrastructure is necessary for each test separately then in each class file, but as a consequence of the infrastructure layers it would crush performance to build a great deal of the same infrastructure over and over when testing the whole group of CostEngines.

So, I believe I still need to have this single initialization method that only runs once before any combination of these (now separated) test classes are run. Is there any nice way to do this?

How test name impact variable persistence between tests in Unittest?

How do I persist changes made within the same object inheriting from TestCase in unitttest? I've referred to Persist variable changes between tests in unittest?. And the following codes works well.

from unittest import TestCase, main as unittest_main

    class TestSimpleFoo(TestCase):

        def setUp(self):
            pass

        def test_a(self):
            TestSimpleFoo.foo = 'can'

        def test_f(self):
            self.assertEqual(TestSimpleFoo.foo, 'can')

    if __name__ == '__main__':
        unittest_main()

However, If I change the test name "test_a" to "test_u", the code will be failed. Anyone can tell how could this happen? thanks.

Writing Unit test for event handlers C#

I need a test case for testing event handlers. In my project, I just pass the total file size value from the Model class to ViewModel class using event handlers.

What are all the ways to write test case for event handlers and what I have to do in my test case?

My test case is not working..

View Model

public RipWatcherWindowShellViewModel(IWorkflowManager workflowManager)
{
    WorkflowManager = workflowManager;
    workflowManager.GetTotalUsfFileSize += workflowManager_GetTotalFileSize;
}


/// <summary>Delegate for workflowManager get total file size</summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The FileSizeChangedEventArgs object</param>
public void workflowManager_GetTotalFileSize(object sender, FileSizeChangedEventArgs e)
{
    if(e.FileSize== 0)
    {
        throw new ArgumentException("We cannot calculate progress percentage because total file size is 0");
    }
    TotalUsfFileSize = e.FileSize;
}

Model

public event EventHandler<FileSizeChangedEventArgs> GetTotalUsfFileSize;

public void StartWorkflow()
{           
    totalFileSize= jobWatcher.StartWatching(HotFoldersCollection);

    //Event handler invoked here....

    GetTotalUsfFileSize.SafeInvoke(this, new FileSizeChangedEventArgs(totalFileSize));
}

Event Handler

public class FileSizeChangedEventArgs:EventArgs
{

    public FileSizeChangedEventArgs (Double fileSize)
    {
        FileSize = fileSize;
    }

    public Double FileSize
    {
        get;
        private set;
    }
}

My Test case

[Test]
public void IsGetTotalFileSizeEventFired()
{
    worflowManager = new Mock<IWorkflowManager>().Object;

    ripWatcherWindowShellViewModel = new RipWatcherWindowShellViewModel(worflowManager);
    ripWatcherWindowShellViewModel.TransferredFileSize += delegate { eventRaised = true; };

    Assert.IsTrue(eventRaised);
}

e2e or Unit Test a Chrome Plugin that reads live website data

I have a contact scraper chrome extension that works with a few different target websites allowing the user to extract structured data for further processing.

It modifies the DOM of the target website and injects a data collection button that pushes into an angular form running in the chrome extension.

Everything works fine, but my problem is that the underlying websites sometimes change their structures and I would like to run a test regularly against the target sites to pickup any issue.

I have used some Javascript Unit Test environments before such as mocha, should and would like to use a something like these for this inside of the chrome extension.

The articles I've currently read, talk about mocking out chrome api's which is fine for just testing your functions, but not so good about testing against the target websites.

What I want to do is set the current address bar to a specific URL, wait for that DOM to load, then iterate over the DOM searching for expected content selectors.

I'm wondering if anyone has any guidance towards solving this problem?

Contact Scraper

Good reasons for unittests

Unfortunately i work in a software development department where there are no tests so far. I am looking for good examples where missing unittests led to catastrophe. Does anyone have such examples?

Rails 4 testing nested resources with multiple URL params

I have been at this for a few hours, still can't figure it out. I have 2 tests on 2 actions on a nested resources controller. requests is the parent resources route, and response is the nested resources route.

These 2 tests give me a no route matches error. Does not make sense. In the first test, it tries to run the update action instead of the edit. Here are my tests:

test "should get edit" do
  assert_routing edit_request_response_path(@myresponse.request_id, @myresponse), { :controller => "responses", :action => "edit", :request_id => @myresponse.request_id.to_s, :id => @myresponse.id.to_s }
  get :edit, params: { id: @myresponse, request_id: @myresponse.request_id }
  assert_response :success
end

test "should update response" do
  post :update, :request_id => @myresponse.request_id, response: { body: @myresponse.body, request_id: @myresponse.request_id, status: @myresponse.status, subject: @myresponse.subject, user_id: @myresponse.user_id }
  assert_redirected_to response_path(assigns(:response))
end

Here are the errors:

3) Error:
ResponsesControllerTest#test_should_get_edit:
ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"responses", :params=>{:id=>"980190962", :request_id=>"999788447"}}
test/controllers/responses_controller_test.rb:43:in `block in <class:ResponsesControllerTest>'


4) Error:
ResponsesControllerTest#test_should_update_response:
ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"responses", :request_id=>"999788447", :response=>{:body=>"This is the body", :request_id=>"999788447", :status=>"draft", :subject=>"This is the subject", :user_id=>"175178709"}}
test/controllers/responses_controller_test.rb:48:in `block in <class:ResponsesControllerTest>'

Same commit in different branches produces different test results in Travis-ci

Ok, so I've been hit by a weird issue that got me baffled.

I have two branches (master and develop) that are at the same commit (I recently merged develop into master).

When I run the test suite locally, everything passes.

However, in travis-ci, the test suite for the master branch fails for two cases.

What is even weirder is that the tests for the develop branch pass without any problem.

I've diff the relevant failing test files and they are exactly the same (as one would expect).

Does anyone know what the problem might be?


Link to travis: http://ift.tt/1POSi8B

can i run unit tests with super test to check the rout in my app.js file

I am new to node and express. is it ok to run unit test this way.for a basic hello world app. if yes, how should the the path be at

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Here is what i am trying out:

var express = require('express');
var request = require('supertest');

var app = express();
var router = express.Router();

app.get('/somename', function(req, res){
  res.status(200);
});

request(app)
 .get('/somename')
  .expect('Content-Type', /json/)

  .expect(200)
  .end(function(err, res){
    if (err) throw err;
  });


router.get('/', function (req, res){
res.send(' { “Hello”: “World” }');
});

router.get('/a', function (req, res){
res.send(' { “Hello”: “World” }');
});

app.use('/somename', router)

app.listen(4000);

I am using express 4.

Properly configuring default unit test framework Visual Studio C++ 2015

I'm relatively new to C++ and visual studio and I have a couple of questions regarding the best/most efficient way to set up unit tests using the unit test framework that is included in Visual Studio 2015 Community Edition.

Lets say this is the structure of my program-

Solution 'Project1'
  References
  External Dependencies
  Header Files
  Resource Files
  Source Files
     Source.cpp

  UnitTest1
  References
     Project1
  External Dependencies
  Header Files
  Resource Files
  Source Files
     unittest1.cpp

The source.cpp just includes a main method and a couple other methods to just keep a basic example. unittest1.cpp just contains a single

Assert::AreEqual(some number, result of some function from source.cpp);

In order to be able to build the unit test I had to change the properties of 'Project1' to be a static library (.lib). Then I had to list Project1 as a reference for 'UnitTest1'. Then I had to edit the configuration of the linker for 'UnitTest1' so that the directory where Project1.lib is build is added to 'Additional Library Directories', and also add Project1.lib in 'Additional Dependencies' in configuration->linker->input.

I suppose I can stomach doing this every time but then once you build the solution, if I want to build 'Project1' as a .exe again I would have to undo all those changes in order to successfully build the solution again.

I'm wondering what's the best way to set up all this configuration so that a person can have a basic unit testing capability while they continue to develop their project? Seems like there's got to be a better way but many of the tutorials I looked at included the steps I mentioned above. To reiterate, I'm just using the unit testing framework that comes packaged with Visual Studio Community edition. I'm open to the use of 3rd party tools that might simplify this process.

Test file write in rails application

I am developing a rails API application for an iphone app. Some of the endpoints lead to functions that write data into a file and stores it in a directory. Everything works fine but every time I run a test for one of these specific endpoints a file is written. Is it possible to get the file to automatically be removed once the test is complete?

More info: I am using RSpec with shoulda_matchers and FactoryGirl in case it is any use.

Entity Framework 5 disable object mocking

My apologies in advance that I am not an EF export. My team have inherited a MVC3 project using EF5 on .NET 4.0. There are a lot of mock objects automatically generated by TT(?) template. We have multiple developers working on the project and constantly causing conflicting errors on the mock objects and we wonder if it is possible to tweak EDMX NOT to generate the mock objects? We tried to delete the test files but they seem to get generated every time we updates the EDMX.
We know that it's a good practice to automate the unit testing but we are running out of time and the budget would not allow us to spend too much time automating unit tests. Thanks in advance.

Boost unit test fails with a "homemade" class in my eclipse project

I'm adding boost unit test to an already working eclipse project with the well known pure virtual Shape class and a derived Circle class. I'm able to calculate radius, perimeter, area etc., nothing spectacular.

If the answer is obvious I have moved my question to the top so you don't have to read through what works and what doesn't. It was originally at the bottom.

Do I need two separate eclipse-projects, one with the tests, and one with the release/debug builds?

I have added C/C++ Unit Testing Support in eclipse (mars edition) on os x and installed boost test via macports. I followed the advise having a separate folder for test as given here.

I have excluded the test-folder from the release build process and have excluded the project-folder from debug-build ditto. I have also added the source folder as Include path in Settings for the test-folder and added test framework library. Running a simpel test works.

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

#include "Circle.hpp"

int add(int i, int j)
{
    return i + j;
}

BOOST_AUTO_TEST_CASE(equal)
{
    BOOST_CHECK(add(2, 2) == 4);
}

The test example is from here. Trying to compile with the Circle-class fails. Autocomplete works so it pulls the header file into the test-folder.

BOOST_AUTO_TEST_CASE(shape)
{
    gnome::Circle c1;
}

The error is

Undefined symbols for architecture x86_64:
  "gnome::Circle::Circle()", referenced from:
      shape::test_method() in test_main.o
  "gnome::Circle::~Circle()", referenced from:
      shape::test_method() in test_main.o
ld: symbol(s) not found for architecture x86_64

and the solution would be to add the object files from the build phase but I don't have the C++ Linker option in Properties->C/C++ Build->Settings for the test-folder, only for the project-folder.

This SO answer indicates to code first and then add tests. But that defeats the purpose of unit testing.

Testing & Analysis of Shell (Bash) Scripts?

I'm working on a project where we deploy our software to Linux machines. This involves a whole load of Bash, for example, the init scripts (e.g. service foo start for SysVinit. My big concern is that we don't test these the way we test the application layer code with JUnit, FindBugs etc as part of our CI pipeline. What solutions are usually relied upon here? Is it possible to test and analyse these low level Linux scripts the way we would the app layer code?

AngularJS Unit Test Array with Karma

I created an app of a calendar and I am trying to create a unit test to show where Jan 1, 2016 will show up on the calendar's array which should be at

$scope.weeks[0][5]

. However, when I test my array I keep getting an undefined on the first element on the array.

Here is the error:

TypeError: Cannot read property '0' of undefined

Not sure where I am going wrong. Any help would be appreciated.

Here is my unit test code:

describe('correctDate', function(){
    var $scope, ctrl;
    beforeEach(module("calendarDemoApp"));
    beforeEach(inject(function($controller, $rootScope){
        $scope = $rootScope.$new();
        ctrl = $controller('MonthCtrl', {
            $scope: $scope
        });
        $scope.today = "Fri Jan 01 2016";
    }));
    fit('should be the 5th element in array', function(){
        console.log($scope.today);
        expect($scope.today).toBe($scope.weeks[0][5]);
    });
});

Here is the code from my app:

angular.module('calendarDemoApp', [])
    .controller('MonthCtrl', function($scope){
        $scope.$watch('date', function(newDate){
            var range = CalendarRange.getMonthlyRange(new Date(newDate.year, newDate.month, 1));
            var totalWeeks = range.days.length/7;           
            var weeks = [];
            for(i=0; i<totalWeeks; i++){
                weeks[i] = [];
                for(j=0; j<7; j++){
                    weeks[i].push(range.days[j+(i*7)]);
                }
            }
            $scope.weeks = weeks;
        }, true);
})

SUT - Testing Internal Behaviour TDD

I have a question about testing requirements.

Let's take example:

Class Article {

    public void deactive() {//some behaviour, which deactives article}

}

I have in my requirements, that Article can be deactived. I will implement it as part of my Article class.

Test will call deactive method, but what now? I need to check at the end of the test, if requirement was fulfilled so I need to implement method isDeactived.
And here is my question, if I really should do it? This method will be only used by my test case, nowhere else. So I am complicating my class interface, just to see assert, if is really deactived.

What is the right way to implement it?

Unit test framework for c++11 like NUnit

Coming from the managed code world with NUnit as unit testing framework.

I've found that there is a jungle of unit test frameworks out there that more or less covers some of the usecases I need(a little disappointing but not bad):

Unit Testing framework for C++

State of the art C++ Unit Testing?

Comparison of c++ unit test frameworks

http://ift.tt/1RU0Tai

How do you implement unit-testing in large scale C++ projects?

http://ift.tt/1xB2ZlV

http://ift.tt/1P5Uymn

But there are several problems in those answers as mentioned below:

  • Mostly opinion based, as they don't actually tell us about the features the recommendations fulfill
  • Old, most of these articles are mentioned before c++ 11 standard and therefore these answers are not refurbished with new standards
  • Incomplete, even when you visit the documentations of those aforementioned libraries, their docs seems to be inadequate and therefore inconclusive. It looks like that someone has to actually experience them in order to know their features.

So I've decided to ask such question again even though it's generally considered off-topic(but not in this case).

Well back to the topic, the features that I require are mentioned below:

  • It should be very flexible, or at least flexible enough, to allow me choose the test cases or test suites interactively(GUI) as well as in batch mode via command line.
  • Well defined, There should be enough macro defined definitions in the unit test framework for separation of test cases and test suites as well as different required assertions that are available in an standard unit test framework(e.g assert true false exception empty or null not empty or not null)
  • Self-sustainable unit tests are very good but MAIN LESS unit tests are preferred, which could be ran in a batch with a shell(bat) script using single convention and a bunch of shared(dynamic) portable libraries(just like NUnit), so it should be either self sustaining or main less.
  • IDE support, which is important too, because it eases the development process of these test cases as well as test running them(testing the testcase!)
    • Good documentation: it is very much preferred if the unit test framework is one go and doesn't require grinding to learn the concepts
  • Also any other features that adds to the ease of arranging, writing or performing those test cases are welcome.

    The description of the problem might be a little remote as I have less experience in c++ code compared to managed code(c# java or etc which compile to intermediate binaries making them easy to interact)

Very long delay when running C# unit test in VS2015

I have a very long delay (about 1 minute! even more) when running unit test in VS2015. When running even a single test, I see the progress bar in the top of the "Test Explorer", it flows for about a minute, and then I get the test result. The reported test runtime is as expected - very small, few milliseconds.

My question is - how can I debug this? How can I see what is going on in this minute before the test actually starts to run?

Thanks.

Test Not Passing From Redirection

I'm wanting to test to see if a user is NOT authenticated and the user tries to access the dashboard then they are are taken to the login page to submit the form.

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;

class AuthTest extends TestCase {

    use DatabaseTransactions;

    protected $user;
    protected $password = 'testpass123';


    /** @before */
    public function setupUserObjectBeforeAnyTest() {
        $this->app->make('db')->beginTransaction();
        $this->beforeApplicationDestroyed(function () {
            $this->app->make('db')->rollBack();
        });
        $this->user = factory(App\User::class)->create([
            'email' => 'john@example.com',
            'password' => bcrypt($this->password),
        ]);
    }

    /** @test */
    public function a_user_is_redirected_to_dashboard_if_authenticated_and_tries_to_access_login_page()
    {
        $this->actingAs($this->user)
            ->visit(route('login'))
            ->seePageIs(route('dashboard'));
    }

    /** @test */
    public function a_user_is_redirected_to_login_page_if_not_authenticated_and_tries_to_access_dashboard()
    {
        $this->visit(route('dashboard'))
            ->seePageIs(route('login'));
    }
}

In the results from the test below it fails. The word app is a route group prefix.

    1) AuthTest::a_user_is_redirected_to_login_page_if_not_authenticated_and_tries_to_access_dashboard
Did not land on expected page [http://localhost/app/login].

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/app/login'
+'http://localhost/app/dashboard'

How to mock a builder using JMockit

I need to mock a builder. Lets say: UriComponentsBuilder; I need to mock the static method: fromHttpUrl to return a mocked instance of itself, so that the other methods likes queryParam or build can be handled.

If I mark the instance to be returned from fromHttpUrl as @Injectable, it keeps throwing "Class already mocked".

How can I achieve this?

samedi 30 janvier 2016

Unexpected method call, but only with a PartialMock...?

I'm tearing my hair out trying to figure out why I can successfully establish method call expectations on a mock object (using PowerMock) when I create a regular mock (i.e. by calling PowerMock.createMock()), but not when I use a partialMock (by calling PowerMock.createPartialMock()) and adding the methods to be mocked.

The code below shows two tests (I'm not asserting anything here, just demonstrating the failure). The first one runs with no errors. The second is exactly like the first, except I create a partial mock. The second test throws an Assertion error (text of error at bottom of post) claiming an unexpected method call to "Bluetooth.getName()", as though I didn't setup the expectation properly. But I use the same expectation setup as in the first test!

I'm somewhat new to Partial Mocks, so maybe I'm missing something, but I've setup my code according to PowerMock's docs and the numerous examples that I've examined.

Note that the class that I'm trying to mock is the Android BluetoothDevice class. It's a final class (which is why I'm using PowerMock). I'm not sure if that matters (and can't imagine why that would work with a normal mock but not a partial mock), but I thought I'd mention it just in case.

Thanks for any help.

public class PartialMockTests
{
@Test
public void testNormalMock()
{
    BluetoothDevice normalMock = PowerMock.createMock(BluetoothDevice.class);

    // tell EasyMock to expect call to mocked getAddress()
    EasyMock.expect(normalMock.getName()).andReturn("fakeName");
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(normalMock);

    //Exercise the mock
    normalMock.getName(); // No error here!

    EasyMock.verify(normalMock);
}

@Test
public void testPartialMock()
{
    BluetoothDevice partialMock =
            PowerMock.createPartialMock(
                    BluetoothDevice.class,
                    "getName", "toString");  //If I don't mock "toString", I get a NPE

    // tell EasyMock to expect call to mocked getAddress()
    EasyMock.expect(partialMock.getName()).andReturn("fakeName");
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(partialMock);

    //Exercise the mock
    partialMock.getName(); // Now I get a Assertion Error:  Unexpected Method Call!  Why?

    EasyMock.verify(partialMock);
}
}

Here is the Assertion Error text: java.lang.AssertionError: Unexpected method call BluetoothDevice.getName(): at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94) at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97) at android.bluetooth.BluetoothDevice$$EnhancerByCGLIB$$6c62bd71.getName() at my.domain.package.PartialMockTests.testPartialMock(PartialMockTests.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 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.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Why doesn't my unit test reflect the changes to my records that PRY shows me exists?

I have a before :each in my specs that looks like this:

  before :each do
    @user1 = create(:user, gender: 0)
    @user2 = create(:user)
    @membership1 = create(:membership, member: nil, family_tree: @user1.family_tree, inviter: @user1, invited: @user2, relation: "sister", relative_type: 1)
    @membership2 = create(:membership, member: nil, family_tree: @user2.family_tree, inviter: @user2, invited: @user1, relation: "brother", relative_type: 1)
    @connection = create(:connection, inviter_membership: @membership1, invited_membership: @membership2, inviter_user: @user1, invited_user: @user2, request_status: 1)
    sign_in @user1
  end

And this is my unit test in question:

  it "should swap ownership of the inviter_membership - aka make invited_user the inviter_user on that inviter_membership" do
    delete :destroy, id: @user1
    expect(@membership1.inviter).to be @user2
  end

All my controller does is destroys the record passed in via the ID, like so:

  def destroy
    @user = User.find(params[:id])
    if @user.destroy
      redirect_to root_path, notice: "You have successfully cancelled your account."
    else
      redirect_to :back
    end
  end

However, in my User model, I have a before_destroy :callback and my associations like so:

class User < ActiveRecord::Base
  before_destroy :convert_user_to_members

  has_many :memberships
  has_many :inviter_memberships, class_name: "Membership", foreign_key: "user_id"
  has_many :invited_memberships, class_name: "Membership", foreign_key: "invited_id"
  has_many :inviter_connections, class_name: "Connection", foreign_key: "inviter_user_id"
  has_many :invited_connections, class_name: "Connection", foreign_key: "invited_user_id"

  private

    def convert_user_to_members
      inviter_mems = self.inviter_memberships
      if !inviter_mems.empty?
        inviter_mems.each do |membership|
          if membership.user?
            member = Member.create(first_name: self.first_name, last_name: self.last_name, email: self.email, bio: self.bio, gender: self.gender, avatar: self.avatar, birthday: self.birthday, deceased: false)
            invited_user = membership.invited
            membership.update!(member: member, inviter: invited_user, invited: nil, relative_type: 0)
            if !membership.inviter_connection.nil?
              connection = membership.inviter_connection
              connection.update!(inviter_membership: membership, invited_membership: nil, inviter_user: invited_user, invited_user: nil, request_status: 3)
            end
          end
        end
      end
    end

For the first binding.pry which is at the top of my test (i.e. before the destroy is called and the callback executed) this is what I get at my console:

   78:       it "should swap ownership of the inviter_membership - aka make invited_user the inviter_user on that inviter_membership" do
 => 79:         binding.pry
    80:         delete :destroy, id: @user1
    81:         binding.pry
    82:         expect(@membership1.inviter).to be @user2
    83:       end
    84:       #

[1] pry()> @user1.name
=> "Maybell McKenzie"
[2] pry()> @user2.name
=> "Joey Stanton"
[3] pry()> @membership1.inviter.name
=> "Maybell McKenzie"
[4] pry()> @membership1.invited.name
=> "Joey Stanton"
[5] pry()> @membership1.member
=> nil

For the second binding.pry, that gets executed within my callback, this is what happens:

    226:             invited_user = membership.invited
    227:             membership.update!(member: member, inviter: invited_user, invited: nil, relative_type: 0)
 => 228:             binding.pry
    229:             if !membership.inviter_connection.nil?
    231:               connection = membership.inviter_connection
    232:               connection.update!(inviter_membership: membership, invited_membership: nil, inviter_user: invited_user, invited_user: nil, request_status: 3)
    233:             end

[6] pry(#<User>)> self.name
=> "Maybell McKenzie"
[7] pry(#<User>)> invited_user.name
=> "Joey Stanton"
[8] pry(#<User>)> membership.inviter.name
=> "Joey Stanton"
[9] pry(#<User>)> membership.invited
=> nil
[10] pry(#<User>)> membership.member.name
=> "Maybell McKenzie"

Notice a few things:

  • the record currently being evaluated is a user record, that has the same name as @user1 in the first binding.pry - which is good.
  • the invited_user is correctly set to the same user record as @user2 above.
  • the membership.inviter.name is now the same as invited_user.name...aka...the swap has been successful.
  • the membership.invited attribute is now set to nil.
  • there is now a membership.member attribute and it is correctly set to the same user as @user1.

So, we are good so far. The next binding occurs AFTER the destroy has been completed. This is where things go awry. Remember there are no dependent: :destroy on any of the membership associations in my User model.

But this is the outcome of the third binding.pry:

    78:       it "should swap ownership of the inviter_membership - aka make invited_user the inviter_user on that inviter_membership" do
    79:         binding.pry
    80:         delete :destroy, id: @user1
 => 81:         binding.pry
    82:         expect(@membership1.inviter).to be @user2
    83:       end

[2] pry()> @user1.name
=> "Maybell McKenzie"
[3] pry()> @user2.name
=> "Joey Stanton"
[4] pry()> @membership1.inviter.name
=> "Maybell McKenzie"
[5] pry()> @membership1.invited.name
=> "Joey Stanton"
[6] pry()> @membership1.member
=> nil

Notice that everything looks identical to the first binding.pry.

If you dig deeper, you will notice that it seems that the record associated with @membership1 was actually destroyed....despite the fact that it shouldn't have been.

[7] pry()> Membership.count 
=> 1 # this should be 2, because no membership record should be deleted.
[8] pry()> Membership.all
=> [#<Membership id: 1986, family_tree_id: 34158, user_id: 14266, created_at: "2016-01-31 05:29:37", updated_at: "2016-01-31 05:29:37", relation: "brother", member_id: nil, invited_id: 14265, relative_type: 1>]
[9] pry()> @user1.id
=> 14265
[10] pry()> @user2.id
=> 14266

So why does the result of my test, not sync up with the results returned by my callback? Or how do I see the exact results sent from my callback to the test? There anyway for me to inspect that?

Unit testing asynchronous function which connects to database

Well I have some functions which connect to database (redis) and return some data, those functions usually are based on promises but are asynchronous and contain streams. I looked and read some things about testing and I chose to go with tape, sinon and proxyquire, if I mock this function how I would know that it works?

The following function (listKeys) returns (through promise) all the keys that exist in the redis db after completes the scanning.

let methods = {
    client: client,
    // Cache for listKeys
    cacheKeys: [],
    // Increment and return through promise all keys
    // store to cacheKeys;
    listKeys: blob => {
        return new Promise((resolve, reject) => {
            blob = blob ? blob : '*';

            let stream = methods.client.scanStream({
                match: blob,
                count: 10,
            })

            stream.on('data', keys => {
                for (var i = 0; i < keys.length; i++) {
                    if (methods.cacheKeys.indexOf(keys[i]) === -1) {
                        methods.cacheKeys.push(keys[i])
                    }
                }
            })

            stream.on('end', () => {
                resolve(methods.cacheKeys)
            })

            stream.on('error', reject)
        })
    }
}

So how do you test a function like that?

Rails model test - should_receive method not working

I'm writing a pretty straightforward method. Whenever a referer has referred 5 people to become new users, I want them to get a refund. This means that when a new user is created, there's a method check_referer that checks to see if the person who referred them (if this person exists) should get a refund because they've now referred 5 people in total.

In the test logs, based on the puts statement, I can tell that the code is working and the refund_membership_fees_paid method is indeed being called once. But the test keeps failing with:

Failure/Error: @referer.should_receive(:refund_membership_fees_paid).exactly(1).times
   (#<User:0x007fbf46bf1c58>).refund_membership_fees_paid(any args)
       expected: 1 time with any arguments
       received: 0 times with any arguments

Test code:

describe User, "Test refund_membership_fees_paid method is called" do
  before do
    @referer = User.new()
    @referer.save(validate:false)
    RefererRefundAlert.stub_chain(:new, :async, :perform)
  end
  it "at 5 users" do
    5.times do |index|
        u = User.new(referred_by: @referer.id)
        u.save(validate:false)
    end
    @referer.should_receive(:refund_membership_fees_paid).exactly(1).times
  end
end

Model code:

def check_referer
  if self.referred_by.present? && User.where(referred_by: self.referred_by).count == 5
    User.find(self.referred_by).refund_membership_fees_paid
  end
end

def refund_membership_fees_paid
  puts "refund_membership_fees_paid method"
  RefererRefundAlert.new.async.perform(self.id)
end

How can I make Cocoapods.org discover that my pod has Tests?

I've got a pod on Cocoapods with tests, but cocoapods.org is saying the pod has no tests. How can I do it? What I'm doing wrong?

http://ift.tt/1Jqi3JQ http://ift.tt/1nvjGM5

OpenPojo IncompatibleClassChangeError Exception

I'm using OpenPojo for validating getter and setter methods of a class. But while trying to validate my getter and setter methods I'm having following exception:

java.lang.IncompatibleClassChangeError: class com.openpojo.reflection.java.bytecode.asm.SubClassCreator has interface org.objectweb.asm.ClassVisitor as super class

My class:

public final class ClientToken implements RememberMeAuthenticationToken {

private static final long serialVersionUID = 3141878022445836151L;

private final String clientName;

private final Credentials credentials;

private String userId;

private boolean isRememberMe;

public ClientToken(final String clientName, final Credentials credentials) {
    this.clientName = clientName;
    this.credentials = credentials;
}

public void setUserId(final String userId) {
    this.userId = userId;
}

public void setRememberMe(boolean isRememberMe) {
    this.isRememberMe = isRememberMe;
}

public String getClientName() {
    return this.clientName;
}

public Object getCredentials() {
    return this.credentials;
}

public Object getPrincipal() {
    return this.userId;
}

@Override
public String toString() {
    return CommonHelper.toString(ClientToken.class, "clientName", this.clientName, "credentials", this.credentials,
            "userId", this.userId);
}

public boolean isRememberMe() {
    return isRememberMe;
}
}

Does anybody help me why this problem occurs.

gulp-mocha halts on first failed test

When running gulp-mocha, if an unhandled error occurs during a test, I'd like that specific test to fail, but the remaining tests to continue. Currently, gulp-mocha halts on the first test which throws an error and outputs the error to the console. I'm running my tests as gulp test, here is my gulp task:

gulp.task("test", ["build"], () => {
    return gulp
        .src("./out/test/*.js", { read: false })
        .pipe(mocha({ reporter: "spec" }))
        .on("error", () => false);
});

If I run my tests directly via mocha ./out/test/, all tests are run regardless of outcome and the errors are shown at the end of the test run. This is what I want.

Unit Testing Strategy, Ideal Code Coverage Baseline

There's still not much information out there on the XCode7 and Swift 2.0 real-world experiences from a unit testing and code coverage perspective.

While there're plenty of tutorials and basic how-to guides available, I wonder what is the experience and typical coverage stats on different iOS teams that actually tried to achieve a reasonable coverage for their released iOS/Swift apps. I specifically wonder about this:

1) while code coverage percentage doesn't represent the overall quality of the code base, is this being used as an essential metric on your team? If not, what is the other measurable way to assess the quality of your code base?

2) For a bit more robust app, what is your current code coverage percentage? (just fyi, we have hard time getting over 50% for our current code base)

3) How do you test things like:

  • App life-cycle, AppDelegate methods
  • Any code related to push/local notifications, deep linking
  • Defensive programming practices, various piece-of-mind (hardly reproducible) safe guards, exception handling etc.
  • Animations, transitions, rendering of custom controls (CG) etc.
  • Popups or Alerts that may include any additional logic

I understand some of the above is more of a subject for actual UI tests, but it makes me wonder:

  • Is there a reasonable way to get the above tested from the UTs perspective? Should we be even trying to satisfy an arbitrary minimal code coverage percentage with UTs for the whole code base or should we define that percentage off a reasonably achievable coverage given the app's code base?
  • Is it reasonable to make the code base more inflexible in order to achieve higher coverage? (I'm not talking about a medical app where life would be in stake here)
  • are there any good practices on testing all the things mentioned above, other than with UI tests?

Looking forward to a fruitful discussion.

Injecting Mocked objects using FactoryBean

I have a FactoryBean (Spring) defined as follows:

public class AMockFactoryBean extends EasyMockFactoryBean<A>{

    public AMockFactoryBean() {
        super(A.class);
    }

    @Override
    public A getObject() throws Exception {
        MockA a= new MockA();
        a.setB(createMock(B.class));
        return new MockA();
    }
}

The class A has an object of type B autowired:

public abstract class A {

    @Autowired
    protected B b;

}

MockA implements a few abstract classes and EasyMockFactoryBean utilizes the Spring FactoryBean method.

In my app.xml config I have:

<bean id="mockedA" class="AMockFactoryBean" />

My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:testContext.xml")
public class ATest {

    @Autowired
    private A mockedA;

}

Result: mockedA in ATest is autowired correctly, but the autowired field A.b has been set to null by Spring. In debug mode I see how getObject() in AMockFactoryBean is called and how mockedA is given a Mock instance of EasyMock. But when the debugger jumps into the ATest class, mockedA.b is null. Why?

How can I mock just for a non-null value?

Let's say I'm testing following method.

/**
 * Does something. This method throws a {@code NullPointerException}
 * either given string or specified charset is {@code null}.
 * @param s the string
 * @param c the charset
 */
void doSomething(String s, Charset c) {
}

How, when I test, can I make mock for a non-null purpose?

assertThrows(NullPointerException.class,
             new MyObject().doSomething(null, UTF_8));
assertThrows(NullPointerException.class,
             new MyObject().doSomething("", null));

Is there any libraries/methods for mocking a general non-null value?

I tried Mockito.mock and it seems throw an Exception for some invalid types for it can actually mock.

Update

By user2004685's answer, now, I'm curious if I can use anyString or any(Class) like this.

assertThrows(NullPointerException.class,
             new MyObject().doSomething(null, any(Charset.class)));
assertThrows(NullPointerException.class,
             new MyObject().doSomething(anyString(), null));

Why is the Visual Studio 2015 Test Runner not discovering my xUnit v2 Desktop tests

I've read Why is the xUnit runner not finding my tests but my problem is that the Visual Studio Test Runner is simply not showing any tests.

I've looked in the Output window and am not seeing anything in at all under Test in the Show output from tabs.

Unit test function returning function in F#

I have written the following function in F# which, given two points, returns a function representing the line which passes throught the two points:

let getFunction (point1:float*float) (point2:float*float) =
    let x1 = fst point1
    let y1 = snd point1
    let x2 = fst point2
    let y2 = snd point2
    let m = (y2-y1)/(x2-x1)
    let n = y1-x1*m
    fun x -> m*x+n

I would like to unit test this function, but I haven't find how to do it, since I can't use a function in a equality assertion. I have thought about generating a secuence of random points and testing the application of the function against the expected result for each point, but I was wondering if there is a better way.

Do Spring MVC need unit test or just integration test

I'm creating Rest API using Spring Boot (spring mvc, spring-hateoas, spring data jpa, spring-security).

Right now, i start refactoring my code also try to increase code coverage.

What i want to ask, in my controller (Spring MVC) should i write unit test or i just can go with integration test (skip unit test)?

Thanks

How to write unit test for a method without input and output?

My project is a bot telegram.I have a class called Mainclass.I want to test a method of it(SubmitNewsGetNews).This method has no input and output.This method check message received from user and send suitable response.This is my defenition of class and method.

 public class MainClass
{
    enum state : int { _firstState = 0, _submitNewsGetType = 1, _submitNewsGetNews = 11, _reservationGym = 2, _reservationGymGetSans = 22, _pollingForFood = 3, _appointment = 4, _cancelingReservation = 5, _cancelingAppointment = 6, Registeration = 7 };
    public TelegramBot bot;
    private  int stateBot;
    public Message sendMessage;
    private  string tempString;
    public  Message message;
    private  MessageTarget target;
    public void SubmitNewsGetType()
    {

        if (message.Text.Contains("/submitnews"))
        {
           sendMessage = bot.SendMessage(target, "Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return");
        }
        else if (message.Text.Contains("/Elmi") || message.Text.Contains("/Farhangi") || message.Text.Contains("/Honari") || message.Text.Contains("/Amoozeshi")
            || message.Text.Contains("/Varzeshi"))
        {
           sendMessage = bot.SendMessage(target, "Please enter your news: \n\n/Return");

            stateBot = (int)state._submitNewsGetNews;

            tempString = message.Text;

        }
        else
        {
            bot.SendMessage(target, "Non definded! Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return");
        }

    }

And this is my unit test.My problem is I can't initialized Message type.

[TestMethod]
    public void SubmitNewsGetNews_Test()
    {
        MainClass instance = new MainClass();
        Message mess_output;
        //How to set value for a Message type??
        //This line get error
        Message mess_input="/submitnews"
        string expected="Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return";
        if (mess_input is "/submitnews")
        {
            a.SubmitNewsGetNews();
            mess_output= a.sendMessage;
            Assert.AreEqual(mess_output.Text,expected);
        } 
        else if (mess_input is "/elmi" or "/farhangi" or ...)
    else if ....
    }

How can I mock Go functions in my tests?

I have read a few questions on StackOverflow that ask how functions such as time.Now() can be mocked. The solution seems to be to write a struct that implements a particular interface, and then in the tests, pass in that mock instead.

Is there a better way of doing this? Since there is no good enough implementation of a dependency injection container in Golang, I don't want to pass structs around manually, or to create a struct that only has something like this inside:

func (s MyStruct) Now() {
    return time.Now()
}

Because, first, I can't test this function. It might be nothing when you are dealing with one line that has no variables in it, but I have a function that connects to a TCP port. Doing stuff like this would require me to create adapters to everything it uses (eg net.Dial(), time.Now(), io.Copy(), bufio.Read(), and many others).

Second, since there is no DI, I will have to pass structs around, which will end up cluttering my code, rather than making it easier to read like DI does in other languages.

how to set SQLSTATE in mysql to remove a previously set error?

I have a procedure that may encounter some undesiable condition and then do:

    SIGNAL SQLSTATE 
        'ERROR'
    SET
        MESSAGE_TEXT = "Unauthorized action: set permissions",
        MYSQL_ERRNO = 2;

I'm testing this procedure with another sql script, as long as Im calling it in acceptable conditions it works and the tests run to the end, but if I want to test it under conditions where it should set the error state, the test script stops running. So How can I:

A) check that the current sql state is 'ERROR'?

and:

B) can I the reset it back to ok or success so that my test script doesn't stop at the first error and will continue testing other conditions?

vendredi 29 janvier 2016

How to arrange multiple setups in PHPUnit

I've seen how Hierarchical Context Runner works in JUnit and it's pretty awesome.

It allows you to declare multiple setups in a single test class. This is great when you are testing multiple scenarios(it is more like doing BDD) Hierarchical Runner Explanation

Would be nice to have something like this in PHPUnit but, I just can't achieve this.

I've tried using @before annotations in methods after some actual tests,

I tried to declare inner classes but then I discovered that is not allowed in PHP 5, and many other things without success.

Is there a way to achieve this ?

Any help is appreciated. Thanks in advance

How can I access the current URI in a view during testing?

I have a shared view component that changes state based on the current URI. I'm currently accessing that information via request.env['PATH_INFO'], as this seems to be the convention as far as I can tell. However, when running unit tests, this always seems to be nil. This is an issue, because it causes any view with this component to explode.

Setting @request.env['PATH_INFO'] in the body of the test doesn't work, and I'm glad it doesn't because that would be hideous.


How can I access the current URI within a view or controller during testing?


I'm using vanilla Rails unit testing, so answers that don't require me to change my testing framework would be much appreciated.

Mock an anonymous function using proxyquire with Node.js?

Is it possible to mock an anonymous function using proxyquire with Node.js? I have a module I need to mock whose constructor is an anonymous class. Is it possible to use proxyquire to mock this, or is there another way to do this?

The reason I'm using proxyquire is because it's a module that is 'required' by the file I'm writing unit tests for.

An example of the code and the function that is returned is:

var example = require('example')(config);

This returns an anonymous function that takes in config as parameters.

function (config) { return new Example(config); }

Grunt/grunt-karma - limit maximum task duration?

Is it possible to somehow set how long any Grunt task can take? And if the time exceeds the limit, it would fail the task? Something like "abort on stuck" feature?

I'm using grunt-karma to run unit tests and it sometimes hangs on CI server for couple of hours due to some networking issues (probably npm install did not install all dependencies...). If this time limit is not supported by Grunt as such, is there any grunt-karma specific option to use?

How to unit test OpenGL on EC2

Both my local computer and EC2 server is on Ubuntu 14.04. Suppose I am testing a cuda opengl interop code as below.

Test.cu

#include <iostream>

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cuda_gl_interop.h>

__global__ static void CUDAKernelTEST(float *data){
  const int x  = blockIdx.x * blockDim.x + threadIdx.x;
  const int y  = blockIdx.y * blockDim.y + threadIdx.y;
  const int mx = gridDim.x * blockDim.x;

  data[y * mx + x] = 0.5;
}

GLFWwindow *glfw_window_;

void Setup(){
  if (!glfwInit()) exit(EXIT_FAILURE);

  glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

  glfw_window_ = glfwCreateWindow(10, 10, "", NULL, NULL);

  if (!glfw_window_) glfwTerminate();

  glfwMakeContextCurrent(glfw_window_);

  glewExperimental = GL_TRUE;
  if (glewInit() != GLEW_OK) exit(EXIT_FAILURE);
}

void TearDown(){
  glfwDestroyWindow(glfw_window_);
  glfwTerminate();
}

int main(){
  Setup();

  GLuint id;
  glGenBuffers(1, &id);
  glBindBuffer(GL_ARRAY_BUFFER, id);
  glBufferData(GL_ARRAY_BUFFER, 3 * 24 * sizeof(GLfloat), 0, GL_STATIC_DRAW);
  cudaGraphicsResource *vbo_res;
  cudaGraphicsGLRegisterBuffer(&vbo_res, id, cudaGraphicsMapFlagsWriteDiscard);
  cudaGraphicsMapResources(1, &vbo_res, 0);
  float *test;
  size_t size;
  cudaGraphicsResourceGetMappedPointer(
  reinterpret_cast<void **>(&test), &size, vbo_res);
  dim3 blks(1, 1);
  dim3 threads(72, 1);
  CUDAKernelTEST<<<blks, threads>>>(test);
  cudaDeviceSynchronize();
  cudaGraphicsUnmapResources(1, &vbo_res, 0);

  // do some more with OpenGL

  std::cout << "you passed the test" << std::endl;

  TearDown();

  return 0;
}

The current approach is create a hidden window and a context. The code compiles and runs fine on my local machine. However, glfwInit() returns GL_FALSE when run on EC2. If I log the messages sent to the error callback, it shows "X11: The DISPLAY environment variable is missing", which looks like it needs a display monitor to be connected in order for it work.

I tried replacing the Setup and TearDown section from GLFW into SDL or GLX and it returns similar error seemingly also requiring a display monitor attached.

I also try running the code with Xvfb and Xdummy which is supposedly to faked a monitor but I got error message from Xvfb "Xlib: extension "GLX" missing on display ":99", and from Xdummy "Fatal server error: (EE) no screens found(EE)"

I can't be the first one attempting to unit test opengl related code on EC2, but I can't find any solutions after googling around. Please advice, thank you so much.

In Karma unit test how does $timeout get injected?

I am not exactly sure how to ask this so I'll try to do it through code.

This is part of a unit test I wrote.

    var loginAfterCredentialsFailed = function($timeout) {
        // bunch of code
    }

    it('goes to login page because cached credentials were not found',
        inject(loginAfterCredentialsNotFound));

What I don't understand is how $timeout is resolved? Does the inject give you access to $timeout? What else does inject provide?

Thanks in advance.

View missed branches with code coverage in VS 2015

I'm using the code coverage tool in Visual Studio 2015, and it's showing that some branches aren't being covered, but I can't find a way to view which branch specifically is being missed. While I can simply look at the unit tests and figure out which branch is being missed, is there a way to view the branches missed with the code coverage tool?

Installing unit test generator in visual studio 2013 gives error .net framework is not installed

enter image description here

I was searching about unit testing but i found missing create unit test option on method that was available on vs2010, then i find option to install Unit test Generator extension. but this even not installed too..and i have also tried command in command window EditorContextMenus.CodeWindow.CreateUnitTests it also say no command exists

Add reference to other C# projects in visual studio 2015

I have a C# console application project in visual studio 2015. I have a project with name MyPrograms in this solution. There are some classes and a main test method in this project. I have another (C# Unit Test) project in the same solution with name MyUnitTests.
I have set the target framework of MyPrograms to .Net Framework 4 Client Profile and .Net Framework 4.5 of MyUnitTests project. I have also added the reference of MyPrograms project in my MyUnitTests project.

Now I want to access class files of MyPrograms project in my MyUnitTests project. I am accessing class files of MyPrograms project with the using statements in the classes of MyUnitTests project. But I am unable to access those classes.

I have also tried it by changing various target frameworks of both the projects. I have tried different things as well as explained in the following links.

http://ift.tt/1Fp01Ah http://ift.tt/1Qxw4F2

How to mock fs.createReadStream w/ sinon

I am using mocha, supertest and sinon to test this:

stream = fs.createReadStream(somepath);
stream.on('open', function() {
  stream.pipe(res);
});

Here is my test where I am trying to mock the fs.createReadStream() method:

var mockedStream = new stream.Readable();
mockedStream._read = function noop() { };
mockedStream.emit('open');
mockedStream.emit('data', 'mock');
mockedStream.emit('end');
sandbox.mock(fs)
  .expects('createReadStream')
  .returns(mockedStream);

The mock is getting injected correctly, but the open event does not seem to be firing in my code.

PHPUnit Database DefaultTester::_construct() must implement interface error

I'm trying to set up db unit-testing for my zend-framework project using Zend Test PHPUnit, and keep running into an error when I try to instantiate a model class in the test for that model (using PHP ActiveRecord for our models).

Argument 1 passed to PHPUnit_Extensions_Database_DefaultTester::__construct() must implement interface PHPUnit_Extensions_Database_DB_IDatabaseConnection, null given

My Test Class:

require_once realpath(APPLICATION_PATH . '/models/Foo.php');

class FooTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    static protected $connection;

    protected function getConnection()
    {
        if (null == self::$connection) {
            $params = [
                'host' =>'127.0.0.1',
                'port' => '3306',
                'username' =>'user',
                'password' =>'pass',
                'dbname' =>'dbname',
            ];
            $db = Zend_Db::factory('PDO_MYSQL', $params);
            self::$connection = $this->createZendDbConnection(
                $db, 'dbname'
            );
        }
        return self::$connection;
    }

    public function testFooUpdate()
    {
        $fooTable = new Foo(); // breaks here
        ...
    }
}

I'm getting a connection to the database after the call to createZendDbConnection(), so I'm not sure why I'm getting the above error.

How to combine per-env deps with a requirements file with Tox?

I'm trying to test specific versions of Python and Django, but also include a general PIP requirements file of additional dependencies to use for all cases.

As the docs (http://ift.tt/1JMpr2m) explain, you do the first like:

deps =
    django15: Django>=1.5,<1.6
    django16: Django>=1.6,<1.7
    py33-mysql: PyMySQL     ; use if both py33 and mysql are in an env name
    py26,py27: urllib3      ; use if any of py26 or py27 are in an env name
    py{26,27}-sqlite: mock  ; mocking sqlite in python 2.x

and you do the second like:

deps = -r{toxinidir}/pip-requirements.txt
       -r{toxinidir}/pip-requirements-test.txt

but how do you combine these?

If I try to define multiple deps, Tox gives me the error "duplicate name 'deps'", but I don't see a way to combine the dictionary and list notatations for deps.

Simplify redundant unit tests

I recently joined a team working on a project. I believe something is wrong with the way our unit tests are built.

The objective of the solution is to generate dynamic documents, using sentences that display based on different criteria.

Since most criteria are used in many sentences, we have a "common" class which houses all the functions that return true/false depending on the check. Then in each sentence class, we call one or many criteria functions and display or not, depending on the results.

We have a test class for the common class and one for each sentence class in order to have a good code coverage.

My english is not so great so here is an example :

Common.cs
bool CheckThis()...
bool CheckThat()...

CommonTest.cs
TestMethodForTestThis_caseA()
TestMethodForTestThis_caseB()
[TestMethodsForTestThat]

Sentence1.cs
bool CheckConditions(){
    return CheckThis() && CheckThat();
}

Sentence1Test.cs
TestMethod_CheckThisTrue_CheckThatTrue
TestMethod_CheckThisTrue_CheckThatFalse
TestMethod_CheckThisFalse_CheckThatTrue
TestMethod_CheckThisFalse_CheckThatFalse

I am sure you can imagine what it looks like if you add a few additional Checks. The way I see it, the tests in Sentence1Test are redundant and hurt maintainability. However I don't see how we can do differently but I am certain that I am missing something obvious here.

How should we test our "higher" level methods?

Thanks !

How to stop mocha instance started programatically

Is there anyway other way than process.exit() to stop a Mocha instance that was started programmatically?

I run mocha in code something like this:

var mocha = new Mocha({
   'reporter' : 'custom-reporter'
});

mocha.run(function(failures){
    console.log('done');
    // this will make the test stop everything...
    // process.exit()
});

Stopping it with process.exit() works, but that terminates everything... if there is still some processes running in the custom reporter that terminates as well. I need a better way to stop the Mocha instance. Is there an alternative approach?

Why am I getting too few invocations back from this Spock test?

I'm new to the Spock testing framework, and I'm trying to do some testing for an android project I'm working on. These objects I'm currently testing are PJO, so they can be tested with regular Spock. For some reason I keep getting 0 invocations on the isAlive method called on one of my objects, but I know for a fact that it's invoked, sense I've literally run it in a debugger and it gets called. So I'm hoping someone can lead me to knowing what I'm doing wrong.

here's the code I'm testing:

 public void start(int startIndex, boolean overrideDownloadOnCellNetwork){
        this.downloadIndex = startIndex;
        this.overrideDownloadOnCellNetwork = overrideDownloadOnCellNetwork;
        if(checkConnectionType(overrideDownloadOnCellNetwork)){
            this.startTrackDownload();
        }
    }

    // I should simplify this at some point.
    private boolean checkConnectionType(boolean overrideDownloadOnCellNetwork) {
        ConnectivityManager connManager = (ConnectivityManager) masterService.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = connManager.getActiveNetworkInfo();
        if(connection == null){
           broadcaster.broadcastError(DownloadEvent.DownloadEventType.ERROR_NO_NETWORK, downloadIndex);
            this.masterService.stop();
            return false;
        } else if(connection.getType() == ConnectivityManager.TYPE_MOBILE && (userModel.isCellDownloadsAllowed() || overrideDownloadOnCellNetwork)){
            return true;
        } else if (connection.getType() == ConnectivityManager.TYPE_WIFI){
            return true;
        } else {
            broadcaster.broadcastError(DownloadEvent.DownloadEventType.ERROR_NO_WIFI_CELL_DOWNLOAD_NOT_ALLOWED, downloadIndex);
            this.masterService.stop();
            return false;
        }
    }


    private void startTrackDownload(){
        if(trackList.size() > 0) {
            if (!downloadThread.isAlive()) {
                downloadThread.start();
            }
            downloadThread.downloadTrack(downloadIndex, trackList.size(), bookModel.getBookID(), userModel.getSessionID());
        }
    }

and here's my test code: Note downloadThead is a Mock of the actual class, which extends java.lang.Thread

def "should check if download thread is alive"(){
    given:
    def mockConnectionManager = Mock(ConnectivityManager)
    def mockNetworkInfo = Mock(NetworkInfo)
    masterService.getContext().getSystemService(Context.CONNECTIVITY_SERVICE) >> mockConnectionManager
    mockConnectionManager.getActiveNetworkInfo() >> mockNetworkInfo
    mockNetworkInfo.getType() >> ConnectivityManager.TYPE_MOBILE

    when:
    downloader.start(0, true)

    then:
    1 * downloadThread.isAlive()
}

Any help would be greatly appreciated. I've tried this in every configuration I can think of... and it always has this same issue.

Unit Testing a watch method call in Directive link function

I have the following Directive

.directive("myContainer", function (myContainerService,$window) {
        return {
            restrict: 'A',
            templateUrl: "myContainer/MyContainer.tpl.html",
            controller: 'myCtrl',
            controllerAs: 'myCtrl',
            scope: {
                items: '='
            },
            link: function (scope, element) {

                var timeout;
                scope.$watch('myCtrl.items', function (items) {
                    var windowWidth = $window.innerWidth - 65;
                    window.clearTimeout(timeout);
                    timeout = window.setTimeout(function () {
                        myContainerService.saveItems(items);
                    }, 1000);
                }, true);
            }
        };
    })

And here is the Unit Test i have.

describe("myCtrl", function(){
        var myCtrl;
        var dirEle ;
        var myScope;
        // var to store the Mock Items
        var myContainerService = $injector.get('myContainerService');
        var items = [..]
        beforeEach(inject(function($compile, $httpBackend){
              $httpBackend.whenGET(/.*my-app\/restful-services\/items*./).respond({...});
            scope.items = myContainerService.getItems();
            dirEle = $compile('<div my-container items="items"></div>')(scope);

            scope.$digest();
            myScope = dirEle.isolateScope();
            myCtrl  = myScope.myCtrl;
        }));

        fit("Saving Items", inject(function($timeout){
            spyOn(myContainerService, 'saveItems');
            //$timeout.flush();
            myScope.$digest();
            $timeout.flush();
            expect(myContainerService.saveItems).toHaveBeenCalledWith(myCtrl.items);
        }));
    });

And my test is failing as the saveItems is not getting called at all. Not sure what i am doing wrong.

Appreciate any inputs.

Thanks

Bypassing mysqli_connect() error to write unit test

I'm trying to write a set of unit tests using PHPUnit (DISCALIMER: This is my first project attempting to use unit tests for improving code quality).

I'm currently have the a "ConnectionManager" class which is managing the connection to the mysql databases. This class has two member functions: GetDBSetLinks and ConnectWithMysqli.

GetDBSetLinks is a function that takes in an array of connection information for multiple mysql databases (each element contains Hostname, Username, etc. and some other info), and passes this information into ConnectWithMysqli.

ConnectWithMySqli() calculates which overload of the mysqli_connect() function the program should use to connect the the mysql database and then calls that overload using the passed in parameters.

When I pass bad connection information (such as a bad password) into GetDBSetLinks() using my unit test, the bad information is handled properly makes it to the ConnectWithMySqli function as expected. When the bad information hits mysqli_connect(), the function fails and triggers the expected "mysql_connect(): Access denied for user 'root'@'192.168.1.113' (using password:YES)" error. The problem is that this also terminates execution of ConnectWithMySqli(), thus ConnectWithMysqli() will not complete and return the variable that I am trying to test against.

What I would like to do is to keep the program running but trigger an exception that can be handled.

Problem is I just started using try{}catch{} and I'm not really sure the best way to do this. Anyone have any ideas?

My two php files can be seen here

Thanks!

Sqlalchemy, tornado and testing unit

I'm having some trouble figuring out how to handle testing with tornado and sqlalchemy... For now all the calls are synchronous to the DB,( WS will handle only real time date from the PLC, not implemented yet).

The biggest "challenge" is how to handle testing that require writes to the mysql DB. I need a second testing schema or to encapsulate every query in a transaction that will be rolled back?

The sqlalchemy file is like this..

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, ForeignKeyConstraint
from sqlalchemy.dialects.mysql import [...]
from sqlalchemy.orm import sessionmaker
import sqlalchemy
from sqlalchemy.engine import create_engine


engine = create_engine('mysql+pymysql://root:@localhost/HMI')
Base = declarative_base()


class Alarm(Base):
    __tablename__ = 'alarms'

    id = Column(Integer, primary_key=True)
    event_type = Column(sqlalchemy.types.NVARCHAR(255))
    sub_type = Column(sqlalchemy.types.NVARCHAR(255))
    alarm_id = Column(sqlalchemy.types.DATETIME)
    alarm_event_type = Column(sqlalchemy.types.FLOA
   [... other tables...]
try:
    Base.metadata.create_all(engine)
except Exception as e:
    print (e)
Session = sessionmaker(bind=engine)

While the application is runned by:

class TornadoBoilerplate(tornado.web.Application):
    def __init__(self):
        tornado.web.Application.__init__(self, urls.url_patterns, **settings)

def main():
    app = TornadoBoilerplate()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

and every query is performed by a :

session = Session()
session.query([...])

How can I perform testing? Any tips?

Register a Moq mock object as type for a Unity container

Since my sut class has a constructor with a IUnityContainer as parameter I like to setup a new Unity container im my unit test and pass it to the sut. I like to use Moq here because I also have to veryfy for certain method calls. What I've tried here is

public interface IFoo
    {
        void Bar();
    }

    class Program
    {
        static void Main(string[] args)
        {
            var fooMock = new Mock<IFoo>();

            fooMock.Setup(x => x.Bar()).Callback(() => Console.WriteLine("Hello"));

            IUnityContainer container = new UnityContainer();
            container.RegisterType(typeof (IFoo), fooMock.Object.GetType());

            var sut = container.Resolve<IFoo>();
            sut.Bar();

            Console.Read();
        }
    }

But this results in an ResulutionFailedException. Any ideas what I can do or what might be an alternative to this problem?

Laravel phpunit test is failing. Going to an unexpected page. Only happens in the test

So, I have a page with a button on it with the value "Create". When I click that Create button, without filling out any of the fields, it validates the form and displays error messages on the same page. When I do that in the browser, it works fine, but when I do it with phpunit, it has unexpected results and I do not know why.

Here is my integration test:

public function testCreateValidation()                                     
{ 
    $this->visit(route('patients.indexes.create', $this->patient->id));    
    $this->press('Create');                                                
    $this->seePageIs(route('patients.indexes.create', $this->patient->id));              
}   

And this is the result:

There was 1 failure:
1) Tests\Integration\IndexControllerTest::testCreateValidation
Did not land on expected page [http://localhost/patients/69/indexes/create].

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/patients/69/indexes/create'
+'http://localhost/patients'

/vagrant/vendor/laravel/framework/src/Illuminate/Foundation/Testing/InteractsWithPages.php:141
/vagrant/tests/Integration/IndexControllerTest.php:51

I don't understand why it is being redirected to the patients page.

Here is the Laravel create method that is being tested:

public function create($id)                                                         
{                                                                                   
    $index = $this->indexes->newInstance();                                         
    $patient = $this->patients->findOrFail($id);                                    

    return view('patient.index.create', ['index' => $index, 'patient' => $patient]);
} 

And here is the relevant section of the create view:

<?= Form::open(['route' => array('patients.indexes.store', $patient->id), 'class' => 'form-horizontal']) ?>
    @include('patient.index._form')
    <?= Form::submit('Create', ['class' => 'btn btn-primary']) ?>
<?= Form::close() ?> 

And finally the store method that it is being sent to:

public function store(IndexRequest $request, $id)       
{                                                       
    $index = $this->indexes->newInstance();             
    $index->fill($request->all());                      
    $index->patient_id = $id;                           
    $index->save();                                     

    $patient = $index->patient;                         

    return redirect()->route('patients.edit', $patient);
} 

I am also using a FormRequest to validate the input:

public function rules()                   
{                                         
    return [                              
        'index_title' => 'required',      
        'index_description' => 'required',
    ];                                    
}  

So essentially, since it is failing the validation in the IndexRequest, the IndexRequest should kick it back to the patients.indexes.create view and display errors. But for some reason it's being kicked to the patients page (this ONLY happens in the test, if I try it out by manually clicking the Create button in the browser, it works as expected)

I've had this issue before but have never been able to solve it. Any ideas?

testing angular google Maps searchBox

I am tesing with Jasmine an angular app which relies on google Maps API, especially on the searchBox component

When the user selects an address listed in the searchBox, google js raises the 'place_changed' event, which I capture in my controller.

myapp.directive('googlemap', ["uiGmapGoogleMapApi"
    (uiGmapGoogleMapApi) ->

        restrict: 'EA'
        replace: true
        templateUrl: 'angular_templates/google_map.html'
        scope: {}

        controller: ($scope, $element) ->    
            events = place_changed: (searchBox) ->
                place = searchBox.getPlace()

Question: How can I test with Jasmine that the controller listens to place_changed ?

C# unit testing public properties's namespace cannot be resolved in test calss

I am setting up a unit test project, and am having a weird issue. I can reference my project that the test project is for just fine. I can use objects from the project just fine. The problem is when I am trying to create public properties inside a unit test class, that are objects of the project being tested, the test class then errors saying it cannot resolve the type. I do not understand why that would be. I can better explain through an example below:

The reference below when in the method resolves fine, and builds.

/// <summary>
    /// Testing the default constructor for FundingAccount.cs
    /// </summary>
    public void ConstructorsTest_Default()
    {
        bool success = true;
        try
        {
            PSMIC.Web.Billing.FundingAccount testFundingAccount = new PSMIC.Web.Billing.FundingAccount();

            //was MessageColelction initialized during default constructor
            Assert.IsTrue(testFundingAccount.MessageCollection != null);
        }
        catch(Exception e)
        {
            success = false;
        }

        Assert.IsTrue(success == true);
    }

However, when I try to create a public property in the unit test class, so I can set it in the test class init method to use globally, it cannot resolve the namespace or type?

[TestClass]
public class FundingAccountTest
{
    #region Initialize and Control Flow method(s)

    //this causes error. [The namesppace or type 'PSMIC' could not be found
    public PSMIC.Web.Billing.FundingAccount TestFundingAccount { get; set; }

Any ideas on what I am doing wrong here? Thanks, and happy coding!

Mocking HttpResponse.StatusCode with AutoFixture and Moq

I am using AutoFixture as an auto-mocking container and want to mock an HttpResponse so that I can verify that a specific StatusCode has been set. However, I am getting a NotImplementedException when I call SetupSet:

var response = _fixture.Freeze<Mock<HttpResponseBase>>();
response
    .SetupSet(x => x.StatusCode = It.IsAny<int>());

If I just use a new Mock of HttpResponseBase, I get no exception, but then I would have to write a FreezeMoq extension method as explained in Mark Seemann's Freezing mocks blog post.

What is AutoFixture doing that means I cannot setup a set on virtual property where the base class throws a NotImplementedException, but can when just using Moq?

Testing a React Modal component

I'm sorry, but I've been having the toughest time trying to test closing my React Modal by clicking a button. The Modal is as simple as can be, and I've tried everything I can think of or find, but I still can't query its children.

The Modal component:

var MyModal = React.createClass({
  ...
  render: function() {
    return (
      <Modal className="my-modal-class" show={this.props.show}>
        <Modal.Header>
          <Modal.Title>My Modal</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Hello, World!
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.props.onHide}>Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
});

My goal is to test if that Close button fires the onHide() function when it is clicked.

My test file:

describe('MyModal.jsx', function() {
  it('tests the Close Button', function() {
    var spy = sinon.spy();
    var MyModalComponent = TestUtils.renderIntoDocument(
      <MyModal show onHide={spy}/>
    );

    // This passes
    TestUtils.findRenderedComponentWithType(MyModalComponent, MyModal);

    // This fails
    var CloseButton = TestUtils.findRenderedDOMComponentWithTag(MyModalComponent, 'button');

    // Never gets here
    TestUtils.Simulate.click(CloseButton);
    expect(spy.calledOnce).to.be.true;
  });
});

No matter what I try, I can't seem to find the Close Button.

Unit testing a helper inside a custom provider in angularjs

I have this provider:

angular.module('app').provider('appProvider', function() {
  this.$get = Helper;

  function Helper() {
    function method() {
      return true;
    };

    return {
      method: method
    };
});

When unit testing it, I can reach appProvider, but not the Helper in unit tests. I've been trying this:

describe('test', function() {
  var prov;

  beforeEach(angular.mock.module('app', function(appProvider) {
    prov = appProvider;
  }));

  it('provider', inject(function() {
    expect(prov.Helper.method()).toEqual(true);
  }));
});

And getting this error:

TypeError: 'undefined' is not an object (evaluating 'prov.Helper.method()')

Question is: How do I reach method() in order to evaluate is correct behaviour?

Data not being retrieved from embedded H2 datasource in springboot test

I've used this technique before and specifying all the configuration explicitly. The log indicates it's creating the datasource and loading the scripts:

o.s.j.d.e.EmbeddedDatabaseFactory - Starting embedded database: url='jdbc:h2:mem:balancer;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
o.s.j.d.i.ScriptUtils - Executing SQL script from class path resource [db/migration/V1_0001__create_queue_server_table.sql]
o.s.j.d.i.ScriptUtils - Executed SQL script from class path resource [db/migration/V1_0001__create_queue_server_table.sql] in 20 ms.
o.s.j.d.i.ScriptUtils - Executing SQL script from class path resource [db/migration/V1_0002__queue_server_entries.sql]
o.s.j.d.i.ScriptUtils - Executed SQL script from class path resource [db/migration/V1_0002__queue_server_entries.sql] in 8 ms.
o.s.o.j.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'

I am able to invoke the REST webservice and the call goes through to the Repository but nothing is returned. The application works fine when connecting to mysql and returns data that was loaded. I cannot see what is missing WRT configuration:

Testcase:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {QueueServiceApplication.class, TestConfig.class})
@WebAppConfiguration
@ActiveProfiles({"test"})
public class QueueServiceApplicationTests {

    private static final int EXPECTED_SERVER_COUNT = 10;

    @Autowired
    private WebApplicationContext webCtx;

    private MockMvc mvc;

    @Before
    public void init() {
        mvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
    }

    @Test
    public void successListAll() throws Exception {
    mvc.perform(get("/listall")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$", hasSize(EXPECTED_SERVER_COUNT)));


    }
}

Test configuration object for embedded datasource:

@Configuration
@Profile("test")
public class TestConfig {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .addScript("classpath:/db/migration/V1_0001__create_queue_server_table.sql")
            .addScript("classpath:/db/migration/V1_0002__queue_server_entries.sql")
            .setType(EmbeddedDatabaseType.H2)
            .setName("vitel-balancer")
            .setScriptEncoding("UTF8")
            .build();
    }
}

Launcher:

@SpringBootApplication
public class QueueServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(QueueServiceApplication.class, args);
    }
}

I'm using spring-boot 1.3.2, java 8 update 72

Grails testing a failing domain save in service

I've a Grails (3+) service where a domain object is retrieved from the DB, modified , and then updated in the DB.

class MyService {
    def modifyObject(String uuid) {
        def md = MyDomain.findByUuid(uuid)
        md.someField = true
        if (!md.save()){ 
            throw new MyException()
        }
    }
}

Now I need to test this service method with a negative test, to be sure that the exception is thrown. But I can't figure out how to force a failing save in the service method.

@TestFor(MyService)
@Mock(MyDomain)
class MyServiceSpec extends Specification {

    void "test An exceptionl situation was found"() {
        given: "An uuid"
            def md = new MyDomain(uuid: "123")
            md.save(failOnError: true)

        when: "service is called"
            service.modifyObject("123")

        then: "An exception is thrown"
            thrown MyException
    }
}

Obviously, re-defining the service method in a more functional way (the object is passed directly to the method, modified and returned without save .e.g MyDomain modifyObject(MyDomain md)) will be a good solution since I could create an invalid ad hoc object outside or even invalidate it after the method execution.

But the question is: "is there a way to test the service code as is?"

using protractor to get the disabled attribute on button not working

I'm trying to get the disabled attr on a button it should be "disabled" but I don't seem to be getting the value. New to angular and protractor!

When I inspect the page this is what HTML I get for the button showing disabled is disabled, like it is on the page:

 <button type="submit" class="button primary inverse" ng-disabled="!comment.$dirty && comment.$valid" disabled="disabled">Save</button>

The protractor test below returns 'Expected null to equal disabled'

    var btnSave = element(by.css('.primary'));
    expect(btnSave.isPresent()).toBeTruthy();

    var attr = element(by.css('.primary')).getAttribute('disabled');

    expect(attr).toEqual("disabled");

When I try I get expected '' to equal disabled.

expect(attr).toEqual("disabled");

Any ideas where I'm going wrong?

Thanks

Mocking Jobs in laravel 5.2 Unit testing

I am pretty new to unit testing. I as asked to write unit test in my application. In my application we have controllers and services. I am trying to mock a job called from the controller like this.

$this->expectsJobs(App\Jobs\UploadResponseEmail::class);

This throws the following error

production.ERROR: Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Bus_Dispatcher::dispatch(object(App\Jobs\UploadResponseEmail)). Either the method was unexpected or its arguments matched no expected argument list for this method

the Job has a constructor which expects an argument. I think that is causing error. How can I pass constructor argument here. Any idea ?

Mocking ag-grid as a dependency using Jasmine

I'm using ag-grid in my application. I need to test a toggle tool panel button function. To do this, though, I need access to ag-grid's api. Here is my unit test I've written so far:

it('toggleToolPanel() should change text on button and change isToolPanelShowing boolean value',function (){
    expect(myScope.toggleToolPanel).toBeDefined();
    //myScope.toggleToolPanel();
    //expect(myScope.buttonText).toBe('Hide Tool Panel');
    //expect(myScope.gridOptions1.api.isToolPanelShowing().toBe(true));
    //expect(myScope.gridOptions4.api.isToolPanelShowing().toBe(true));
    //expect(myScope.gridOptions5.api.isToolPanelShowing().toBe(true));
});

I'm getting isToolPanelShowing() is undefined, which doesn't surprise me. I'm just not sure how to load this dependency (ag-grid) into jasmine so it's api becomes available. Will I need to create mock gridOptions (similar to ui-grid) and a mock column definition within my test file?

nodejs: Mockery Examples

I need to mock a html request from the source url using Mockery. I looked at the documentation but could not understand the head or tail of it.

Let say if i want to mock

url = "http://test.server.fr/"

How do i do that using Mockery?

Also if anyone has any examples or Tutorial where I can look deeper into. I tried with google but could not find any links.

Please note it is not PHP Mockery.

Also please dont suggest me any other tools/framework.

Testing Android Realm with RxJava - "opened from a thread without a Looper" Exception

I have the following code, based off the documentation provided by Realm (http://ift.tt/1SNAQlg)

public Observable<Foo> getFooById(String id) {

    realm = Realm.getInstance(realmConfiguration);

    return realm.where(Foo.class)
            .equalTo("id", id)
            .findFirstAsync()
            .asObservable()
            .filter(this::filterResult);
}

This works in App as expected however when it comes to testing things become a little more tricky. I have the following test (stripped down to keep it simple) :

@Test
public void testRealmExample() {

    RealmConfiguration config = new RealmConfiguration.Builder(context)
            .name("test.realm")
            .inMemory()
            .build();

    DataManager dataManager = new DataManager(config);

    TestSubscriber<Foo> testSubscriber = new TestSubscriber<>();
    dataManager.getFoo("").observeOn(AndroidSchedulers.mainThread()).subscribe(testSubscriber);
    testSubscriber.assertNoErrors();
}

When the test is executed the following error occurs java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper. Async queries need a Handler to send results of your query.

To counter this I read on the Realm GitHub page that they use an annotation @UiThreadTest to force the test to run on the UI thread, which from my understanding is a looper thread, therefore this should solve my problem. I added:

@Rule
public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

and changed my test to include the annotation

@Test
@UiThreadTest
public void testRealmExample() { ...}

This still yields the same exception. Does anyone know why and a solution? Thanks.

Handling Expected exception in Unit Test C#

I wrote a test case for checking file path. In that test case I used Expected exception, then I want to know what happen if the method would not throw the file not found exception.

For example, I run the test case in another system if the given file path exists in the system, the test will go to fail. But it should not be, the test case should be pass always.

How to handle that situation because the Unit test is not dependent anything example should not depend on machine?

Test case...

string sourceFilePath = @"C:\RipWatcher\Bitmap.USF_C.usf";

string targetDirectory = @"C:\UploadedRipFile\";

[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void InvalidSourceFilePathThrowsFileNotFoundException()
{
    logWriter= new Mock<LogWriter>().Object;

    ripfileUploader = new RipFileUploader(logWriter);

    ripfileUploader.Upload(@"D:\RipWatcher\Bitmap.USF_C.usf",       
    targetDirectory);            
}

Method..

public void Upload(string sourceFilePath, string targetFilePath)
{
    if (!File.Exists(sourceFilePath))
    {
        throw new FileNotFoundException(string.Format("Cannot find the file: {0}", sourceFilePath));
    }

    if (!Directory.Exists(targetFilePath))
    {
        throw new DirectoryNotFoundException(string.Format("Cannot find the Directory: {0}", targetFilePath));
    }
    try
    {
        fileCopyEx.CopyEx(sourceFilePath,targetFilePath);               
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("Failed to move file {0}", sourceFilePath), ex);        
    }          
}

Verify if a method was called with specific parameters

How can I verify if a certain method was called with specific parameters, but ignore all other invocations. Example

Configuration conf = mock(Configuration.class);
...

//Some code that calls conf methods
conf.set("ignore_me_1", "ignore_me_1") 
conf.set("ignore_me_2", "ignore_me_2")
conf.set("expected_key", "expected_value")  
....

//Now lets verify what was called - it will fail, becasue the other two invocations were not expected. 
verify(conf).set("expected_key", "expected_value") 

How can I tell mockito to ignore the unexpected invocations, and check only for the expected one ?

Here is the error I receive:

Argument(s) are different! Wanted:
abstractConfiguration.setProperty(
    "SOME_BOOL_PROPERTY",
    "false"
);
-> at .......

Actual invocation has different arguments:
abstractConfiguration.setProperty(
    "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds",
    45000
);
-> at ......

Can we drill-down to classes and methods to see method coverage with eCobertura plugin in Eclipse?

In the Coverage Session View, I can see coverage for packages and files, but not for individual methods. Is there a way to see that? Please do not suggest Eclemma, since it doesn't work for PowerMock.

Spy on setTimeout and clearTimeout in Karma and Jasmine

I cannot seem to be able to spy on setTimeout and clearTimeout in my Jasmine tests, which are being run through Karma.

I have tried variations on all of this

spyOn(window, 'setTimeout').and.callFake(()=>{});
spyOn(global, 'setTimeout').and.callFake(()=>{});
spyOn(window, 'clearTimeout').and.callThrough();

clock = jasmine.clock();
clock.install();
spyOn(clock, 'setTimeout').and.callThrough();

runMyCode();

expect(window.setTimeout).toHaveBeenCalled(); // no
expect(global.setTimeout).toHaveBeenCalled(); // nope
expect(window.clearTimeout).toHaveBeenCalled(); // no again
expect(clock.setTimeout).toHaveBeenCalled(); // and no

In every case, I can confirm that setTimeout and clearTimeout have been invoked in runMyCode, but instead I always get Expected spy setTimeout to have been called.

For window, clearly this is because the test and the runner (the Karma window) are in different frames (so why should I expect anything different). But because of this, I can't see any way to confirm that these global functions have been invoked.

I know that I can use jasmine.clock() to confirm that timeout/interval callbacks have been invoked, but it looks like I can't watch setTimeout itself. And confirming that clearTimeout has been called simply isn't possible.

At this point, the only thing I can think of is to add a separate layer of abstraction to wrap setTimeout and clearTimeout or to inject the functions as dependencies, which I've done before, but I think is weird.

java testing junit help wrong input

Ok guys I neeed quick help with my assigment I think it is not something difficult

You see I have to write Bowling Code kata like this

http://ift.tt/1nCkBuI

and I have writen the code for it

Here is my Bowling Class

public class BowlingGame {



    private int roll = 0;
    private int [] rolls = new int[21];


    public void roll(int...rolls){
        for(int pinsDown:rolls){
            if(pinsDown>10){
                throw new IllegalArgumentException();
            }else{
            roll(pinsDown);
            }

        }

    }


    public void roll(int pinsDown){
        rolls[roll++] =pinsDown;
    }


    public int score(){
        int score = 0;
        int cursor = 0;

        for(int frame = 0;frame<10;frame++){
            if(rolls[cursor]==10){ // check if it is strike
                score+=10 + rolls[cursor+1] + rolls[cursor+2];
                cursor++;
            }else if(rolls[cursor] + rolls[cursor+1]==10){ // check if it is spare
                score+=10 + rolls[cursor+2];
                cursor+=2;
            }else{
                score+=rolls[cursor] + rolls[cursor+1];
                cursor+=2;
            }
        }
        return score;

    }

}

and Here is my Testing Class

public class TestBowling {



    private BowlingGame game;

    @Before
    public void setingUp(){
        game = new BowlingGame();
    }

    @Test
    public void canScore60(){
        game.roll(3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3);
        assertThat(game.score(), is(60));

    }



    @Test
    public void canScorePerfect(){
        game.roll(10,10,10,10,10,10,10,10,10,10,10,10);
        assertThat(game.score(), is(300));

    }


    @Test
    public void canScore67(){
        game.roll(3,3,3,3,3,3,3,3,4,6,3,3,3,3,3,3, 3,3, 3,3);
        assertThat(game.score(), is(67));

    }


    @Test
    public void canScore75(){
        game.roll(3,3,3,3,3,3,3,3,4,6,4,6,3,3,3,3, 3,3, 3,3);
        assertThat(game.score(), is(75));

    }


    @Test
    public void canScore70(){
        game.roll(3,3,3,3,3,3,3,3,10,3,3,3,3,3,3, 3,3, 3,3);
        assertThat(game.score(), is(70));

    }


    @Test
    public void canScore87(){
        game.roll(3,3,3,3,3,3,3,3,10,10,3,3,3,3,3, 3,3, 3,3);
        assertThat(game.score(), is(87));

    }


    @Test
    public void canScore70with10(){
        game.roll(3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,10,3,3);
        assertThat(game.score(), is(70));

    }




    @Test
    public void canScore84(){
        game.roll(3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,10,10,10);
        assertThat(game.score(), is(84));

    }


    @Test
    public void canScoreWith3and7(){
        game.roll(3,7,3,7,3,7,3,7,3,7,3,7,3,7,3,7,3,7,3,7,3);
        assertThat(game.score(), is(130));

    }









    //this tests should fail

    @Test (expected = IllegalArgumentException.class)
    public void testing15() {
        int a = 15;
        game.roll(a);

    }



    @Test (expected = IllegalArgumentException.class)
    public void testingLetter() {
        char c = 'c';
        game.roll(c);

    }


}

**My question is how can I test this

Test wrong input with 15 for one throw

with two throws in the same frame bigger than 10

with a letter input

**