mardi 31 mai 2016

Where to put testNG xml file in ANT java web project

I am using testNG in a java web project. When I run the test with gui eclipse on Linux machine it creates a .xml file in my /tmp/ folder. My concern is If I create a custom xml file then where to put that file in project and how we can run that test with eclipse gui.

How to check checkbox in repeater with protractor

I am having difficulty checking a checkbox in an AngularJs repeater with protractor.

The model looks like this:

environments: [
                {
                    name: 'Proof of Concept',
                    checked: false
                },
                {
                    name: 'Non-Production',
                    checked: false
                },
                {
                    name: 'Production',
                    checked: false
                }
            ]

The view like this:

<div class="checkbox" ng-repeat="environment in vm.assessment.environments">
  <label><input type="checkbox" ng-model="vm.assessment.environments[$index].checked" ng-click="vm.checkboxChanged()" ng-required="!vm.someChecked"></label>


</div>

Am getting the repeater in protractor like so:

this.environments = element.all(by.repeater('environment in vm.assessment.environments'));

And trying to check the checkbox like this but when i run the test it does not seem to check it:

this.environments.get(0).click();

How to check radio button automatically with third-party program

I'm making a web that provides multiple choice tests, but I'm too lazy to test it the human way. I want to write a simple C# .Net winform program that help me to check every A (or B, C, D) radio button of the question in the web browser. I wonder if a winform application could do that.

Thank for reading :)

Re-usable components and fixtures in Golang tests

I'm just getting started with Golang and writing my first test suite.

I have a background in Rails, which has fantastic support for testing tools (Rspec, Cucumber, etc..), so I'm approaching my golang tests with a similar mindset (not sure if that's the right or wrong thing to do)

I have a User data model (basically a struct) that reads records from a users table in postgres and stores an array of them. (Essentially a really simple version of what ActiveRecord does in the Rails world)

I'd like to write a test that checks if the routine correctly reads from the DB and builds the models.

  1. In almost every test suite I'll be connecting to the DB so I have a helper named establish_db_connection. Where can I place this so that it's centrally available to all my tests?

  2. Building off #1 - is there an equivalent of a before block or some setup/teardown method where I can establish a connection before every test?

  3. Lastly, how do I handle fixtures? Right now before each test I call a clear_db function that resets all tables and inserts some static data rows. I'd love to move away from fixtures and use factories to build data as needed (very similar to FactoryGirl in Rails), but not sure how common that is in Golang.

  4. Is the built-in go test framework the best approach, or are there better alternatives?

junit - add timers to each @Test annotation in a Test suite (wthout replicating code)

I have a series of test classes in junit and I want to add elapsed time of only each @Test method. I want to bypass the @Before and @After, as I am not interested in the performance of those methods. I would want to start a timer before the first line of of every block of code that already exists beneath every @Test annotation, and then stop the timer on the last line of the block. I'm thinking I want to override the org.junit.Test class and insert the start and stop timers? Is there a better way to do it?

ModelState.IsValid always true when testing Controller in Asp.Net MVC Web Api

I have tried to make this works and made many google/stackoverflow searches with no luck at all.

I have a simple Model:

    public class MovieModel
    {
        public string Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }
    }

A method in the controller:

    // POST: api/Movies
    public IHttpActionResult Post([FromBody]MovieModel movieModel)
    {
        if (ModelState.IsValid)
        {
            //Code
        }
    }

And a test method (is an integration test, but the same would happen in unit tests):

    [TestMethod]
    public void MoviesController_Post_Without_Name()
    {
        // Arrange
        var model = new MovieModel();
        model.Name = "";

        // Act
        var result = controller.Post(model);

        // Assert
        Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
        Assert.AreEqual(6, controller.Get().Count());
    }

Despite the fact that the model is clearly invalid it always evaluate the IsValid property to true.

I tried many approaches so far without success.

Rails test and fixture are not matching

Suppose we have the following models. I have a notion of a user and a band. Users can be part of bands through memberships. Now, there is a notion of a "Notification", which for now is effectively being used to invite members to join a band. A Notification has both a User (effectively the invitee), the Band, and a Creator (should be an admin Member)

class User < ActiveRecord::Base
  has_many :members, dependent: :destroy
  has_many :bands, through: :members
  has_many :notifications
end

class Notification < ActiveRecord::Base
  belongs_to :band
  belongs_to :user,    class_name: "User", foreign_key: "user_id"
  belongs_to :creator, class_name: "User", foreign_key: "user_id"
end

class Band < ActiveRecord::Base
  has_many :members
  has_many :users, through: :members, dependent: :destroy
  validates :name, presence: true, uniqueness: { case_sensitive: false }
end

class Member < ActiveRecord::Base
  belongs_to :user
  belongs_to :band
end

Now suppose we have this record in notifications.yml, where chris and alexander are two different users and h4h is a given band. Suppose that chris has a name column of "Chris Cheveldayoff" and alexander's name is "Alexander Tester"

chris_h4h:
  notification_type: invite
  user:              chris
  creator:           alexander
  band:              h4h
  has_expired:       false

I am writing a test to test a precondition whereby you cannot create an invitation to a given user if such an invitation exists. I'm confident it works correctly in code, but it is failing in the test. I looked into it further and noticed something fishy, and was wondering why. Suppose @chris_not = notifications(:chris_h4h).

puts @chris_not.user.name
puts @chris_not.creator.name

For some reason, both print out "Alexander Tester", and I'm stumped to why this is the case.

Is there a tool/link to test a set of RESTful webservices(Stateless) all together in one place?

I am looking for a one tool/GUI link to test my webserices where i can configure all my RESTFul webservices(Stateless) in one UI and then setup a continous integration/Automation testing of these webservices?

The tool/link should be able to : 1. select any webservice from the list and to be able to handle a custom request and show the response instantly. 2. To be able to configure the end points through GUI 3. to be able to run the automated scripts for the testing.

I did some research and found the tool, Swagger.io but it doesnt have any feature to allow to run automated scripts.

Any inputs/suggestions is appreciated.

Thanks in advance

How to Test Fraud Management Filters paypal

I would like to know how to test the different rules configured in the Fraud Management Filters section. I'm using magento 1.9, and I need to check that Paypal is working with those filters.

thanks

Capybara::ElementNotFound: Can't Find Field

I'm just learning feature specs and I'm running into a problem that I can't quite figure out. Capybara::ElementNotFound: when I try to run my test. It's strange because I'm following a template word for word but I'm still getting this error. I'd love some help! Here is my code and error for clarity.

TEST

require "rails_helper"

RSpec.feature "Create a subscriber" do
 scenario "Customer can sign up as a subscriber" do
  visit "/subscribers/new"

  user = User.create!(email: "user@example.com", password: "password")
  fill_in "Email", with: "user@example.com"
  fill_in "Password", with: "password"
  click_button "Sign in"

  fill_in "first_name", with: "Cam"
  fill_in "last_name", with: "Bass"
  fill_in "email", with: "cam@example.com"
  fill_in "phone_number", with: "8269338"

  expect(page).to have_content("Subscriber Has Been Successfully Created")
 end
end

VIEW

  <%= form_for @subscriber do |form| %>
  <div class="form-group">
  <p>
  <%= form.label :first %>
  <%= form.text_field :first_name %>
  </p>
  <p>
  <%= form.label :last %>
  <%= form.text_field :last_name %>
  </p>
  <p>
  <%= form.label :email %>
  <%= form.text_field :email %>
  </p>
  <p>
  <%= form.label :phone %>
  <%= form.text_field :phone_number %>
  </p>
 </div>
<%= form.submit "Sign Up", class: "btn btn-primary" %>

ERROR enter image description here

Testing multithread when I thow it with maven it.test

I want execute simultaneously all test'methods.

¿It's possible do it from maven when I'm throwing the test using -Dit.test=myTestSuite?

I am trying it, but the test is always executed from the same treahd.

The maven line I use

mvn verify surefire:test -Dit.test=JMOMTestSuite

Part of my pom.xml

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19.1</version>
        <configuration>
            <forkCount>5</forkCount>
            <parallel>methods</parallel>
            <reuseForks>false</reuseForks>
        </configuration>
      </plugin>

My testSuite

package tsol.mentes.tester.suites;

import org.junit.runners.Suite.SuiteClasses;

import tsol.mentes.tester.JMOMTest;

@SuiteClasses({ JMOMTest.class })
public class JMOMTestSuite extends AbstractTestSuite {
    // the tests classes are executed in the order they are included in the
    // SuiteClasses annotation

}

My test

package tsol.mentes.tester;

import org.apache.commons.logging.LogFactory;
import org.junit.Test;

public class JMOMTest extends AbstractTest {

    static {
        log = LogFactory.getLog(JMOMTest.class);
    }

    @Override
    public void setUp() {
        super.setUp();
        System.out.println();
    }

    @Test
    public void testPrueba1() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 1");
    }

    @Test
    public void testPrueba2() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 2");
    }

    @Test
    public void testPrueba3() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 3");
    }

    @Test
    public void testPrueba4() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 4");
    }

    @Test
    public void testPrueba5() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 5");
    }

    @Test
    public void testPrueba6() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 6");
    }

    @Test
    public void testPrueba7() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 7");
    }

    @Test
    public void testPrueba8() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 8");
    }

    @Test
    public void testPrueba9() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 9");
    }

    @Test
    public void testPrueba10() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 10");
    }

    @Test
    public void testPrueba11() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 11");
    }

    @Test
    public void testPrueba12() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 12");
    }

    @Test
    public void testPrueba13() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 13");
    }

    @Test
    public void testPrueba14() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 14");
    }

    @Test
    public void testPrueba15() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 15");
    }

    @Test
    public void testPrueba16() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 16");
    }

    @Test
    public void testPrueba17() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 17");
    }

    @Test
    public void testPrueba18() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 18");
    }

    @Test
    public void testPrueba19() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 19");
    }

    @Test
    public void testPrueba20() throws Exception {
        System.out.println(Thread.currentThread().getName() + " -> Test prueba 20");
    }
}

Protractor: Syntax to select elements based on html attributes

I want to select this element:

 <span class="required" ng-class="{'disabled': saveInProgress}" 
 input-control="{okCallback:setFieldValue, params:['firstName'], 
 title:'First Name', value: person.firstName, 
 validate:{length:100},empty:false}">
     <span hs-placeholder="Type First Name" class="ng-binding"></span>
 </span>

And this one too:

 <span class="required" ng-class="{'disabled': saveInProgress}" 
  input-control="{okCallback:setFieldValue, params:['lastName'], 
  title:'Last Name', value: person.lastName, validate:{length:100}}">
      <span hs-placeholder="Type Last Name" class="ng-binding">
      </span>
 </span>

I tried to do so using

 var input = element(by.css('span.required span.ng-binding'));  
 browser.actions().mouseMove(input).click().perform();

But it kept on calling the first name element only. Any ideas? please :)

robolectric runOnUiThread on a Thread does NOT work

runOnUiThread() does not seem to work when being executed within a thread. Anybody knows of a workaround?

Note: I filed a ticket here - http://ift.tt/25x4uPk

import android.app.Activity;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertTrue;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class RunOnUiThreadTest {

    /**
     * Works
     * @throws Exception
     */
    @Test
    public void inside_the_main_thread() throws Exception {
        final Activity activity = Robolectric.setupActivity(Activity.class);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean didRun = new AtomicBoolean(false);

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                didRun.set(true);
                latch.countDown();
            }
        });

        latch.await(20, TimeUnit.SECONDS);
        assertTrue(didRun.get());
    }

    /**
     * Fails
     * @throws Exception
     */
    @Test
    public void inside_a_new_thread() throws Exception {
        final Activity activity = Robolectric.setupActivity(Activity.class);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean didRun = new AtomicBoolean(false);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        didRun.set(true);
                        latch.countDown();
                    }
                });
            }
        });
        thread.start();

        latch.await(20, TimeUnit.SECONDS);
        assertTrue(didRun.get());
    }

}

What is the best way to test View Model that depends on child view models?

I have class MainViewModel that takes couple of child view models as dependency. I want to test MainViewModel methods. What is the best way to do it? How should I mock child view models?

My code looks like:

public class MainViewModel:ViewModelBase
{       
    public MainViewModel(ChildViewModel1 childViewModel1, ChildViewModel2 childViewModel2)
    {
        this.ChildViewModel1 = childViewModel1;
        this.ChildViewModel2 = childViewModel2;
    }

    public ChildViewModel1 ChildViewModel1 { get; set; }

    public ChildViewModel2 ChildViewModel2 { get; set; } 

    public void MethodThatIWantToTest()
    {
        this.ChildViewModel1.SomeProperty = "new value";
    }
}

public class ChildViewModel1:ViewModelBase
{
    private ISomeService someService;

    public ChildViewModel1(ISomeService someService)
    {
        this.someService = someService;
    }

    public string SomeProperty { get; set;}
}


//Test
public void Should_ChangeChildViewModel1SomeProperty_WhenCallingMethodThatIWantToTest()
{
    // arrange
    var mainViewModel = new MainViewModel(.., ..); // how to mock here??

    // act
    mainViewModel.MethodThatIWantToTest();

    // assert
    Assert.Equal(mainViewModel.ChildViewModel1.SomeProperty, "new value");
}       

Android Alpha Tests : "The requested URL was not found on this server" or "item not found"

I published an alpha version of my game on the android play store to test it. As in this post, everything seems to be fine BUT I cannot access the alpha play store page to download the apk. I followed every solutions I can find on forums (clear cache, keep only one account on my phone, etc) but still no positives results. The alpha is in published state since 1 week.

Has anyone encountered similar delays/issues ? and if so have you found any solutions ?

Thanks

PHP Websocket test authentication

I am trying to test a scenario, that on the one hand, anonymous users should immediately get a disconnect from a Websocket connection and on the other hand, authenticated users should stay in the websocket connection. The first case is easy testable by using the code down under. The authentication process is not working.

For session storage, I am using Cookie authentication in combination with a database: Symfony PDO Session Storage. It's all working fine, but when it comes to testing the described behaviour by using authentication, I don't know how to authenticate the user in a test. As a client, I am using Pawl asynchronous Websocket client. This looks the following:

\Ratchet\Client\connect('ws://127.0.0.1:8080')->then(function($conn) {
    $conn->on('message', function($msg) use ($conn) {
        echo "Received: {$msg}\n";
    });

    $conn->send('Hello World!');
}, function ($e) {
    echo "Could not connect: {$e->getMessage()}\n";
});

I know that as a third parameter, I can pass header information to the "connect" method, but I cannot find a way so that the client is connected and the cookie is passed correctly during the ws handshake. I thought of something like:

  1. Authenticate a client by creating an authentication token
  2. I create a new entry in the session table in database with serialized user
  3. I pass the created cookie as a third argument to the connect method

This is the theory I thought that would work, but the user always stays anonym on websocket side.

For server side websocket implementation, I am using Ratchet, which is being wrapped by the following Symfony bundle: Gos Websocket Bundle

How to authenticate the user when testing websockets?

Splitting Jenkins Job to run concurrently

Does anyone know of a way to split a single Jenkins job into parts and run them concurrently/parallel?

For example if I have a job that runs tests which take 30 minutes, is there a way I can break this job into three 10 minute runs that run at the same time but in three different instances

Thanks in advance.

PyTest: test which function was called in the if statement

I have a function, which considers three different cases and for each case calls a different function, like in the example below

def my_fun(input):
 if input == 1:
    fun1()
 if input == 2:
    fun2()
 if input == 3:
    fun3()

I would like to write a test for function my_fun using py.test, but I don't know how I can test if the proper function was called for a given input?

ReferenceError: fetch is not defined in redux application testing with Mocha

I testing my React-Redux application with Mocha. When I covering async action creators and run npm start I have an error from Mocha

ReferenceError: fetch is not defined;

My Test code:

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as activity from '../../app/actions/activity'
import * as admin from '../../app/actions/admin'
import nock from 'nock'
import {expect} from 'chai'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async functions', () => {
afterEach(() => {
    nock.cleanAll()
})

it('creates FETCH_ACTIVITY_SUCCESS when fething activities has been done', () => {
    nock('http://example.com')
    .get('/dashboard/activity')
    .reply(200, {body : {activityList: [{"label":"Data uploaded","description":" igunchenko@griddynamics.com","activityDate":{"hour":17,"minute":18,"second":28,"nano":0,"dayOfYear":145,"dayOfWeek":"TUESDAY","month":"MAY","dayOfMonth":24,"year":2016,"monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"}}}]}})

    var expectedActions = [
        {type: activity.REQUEST_ACTIVITY},
        {type: activity.RECEIVE_ACTIVITY}
    ]
    var store = mockStore({activityList: []})
    return store.dispatch(activity.fetchActivity())
    .then(() => {
        expect(store.getActions()).toEqual(expectedActions)
    })
})

it('creates FETCH_ADMIN_SUCCESS when fething activities has been done', () => {
    nock('http://example.com')
    .get('/customers')
    .reply(200, {body : {customers: [{"customerId":1,"accountId":24,"active":true,"confirmed":true,"priority":5,"email":"nusateno@griddynamics.com","fullName":"Nikita","company":"Nikita","industry":"Others","phone":"","admin":true},{"customerId":4,"accountId":27,"active":true,"confirmed":false,"priority":5,"email":"1@1.ru","fullName":"The fifth great user","company":"RA test team","industry":"Software, High-Tech","phone":"3537375477","admin":true}]}})

    var expectedActions = [
        {type: admin.REQUEST_CLIENT_LIST},
        {type: admin.RECEIVE_CLIENT_LIST}
    ]

    var store = mockStore({customers: []})
    return store.dispatch(admin.fetchClientList())
    .then(() => {
        expect(store.getActions()).toEqual(expectedActions)
    })
})
})

After this exception I have added

import fetch from 'whatwg-fetch'

and got this:

ReferenceError: self is not defined

How I can solve this problem?

Best way to test apps against test environments

Not sure if this is the right forum and struggling to articulate this questions but here goes:

We have a process in place where we regularly release testflight app builds in order to test new functionality and fixes in our app. We always point these builds at our production environment (API’s, databases, etc). This causes us some issues like:

  • We are regularly trying to test stuff which has not yet been released to production (i.e. backend stuff may have not been updated yet)
  • When we do move code from our backend test environment to our production environment it has potentially not been tested as the app never points there.
  • We dont see what our real production users see as we are always on more advanced builds.

I am sure there are a number of ways we could do this a lot better but a key requirement we have going forward is to be able to release versions of our app which point to our test environment so we can correctly test things end-to-end to help alleviate the above issues. At the same time we also need versions of our app pointing at production as we use the app ourselves day to day.

The two obvious choices that I can come up with are:

Option 1 - Have separate test and production apps

By this I mean we have two apps released with two separate bundle id’s and names (like app_test and app_prod). You can then load both of these apps on your phone at the same time.

Option 2 - Same app built to either point at test or prod

This is basically where I would release the same app pointing at either production or test. You can only have one or the other on your phone at any one time.

Option 1 feels like the right thing to do but I have a number of issues with it:

  • The configuration of push and provisioning certificates will be more complicated

  • Inbound push notifications will be hard to understand and debug on phones if you have the two apps running

  • We would need to either submit a second app to app stores or we will need to use a third party release tool like hockeyapp or whatever.

  • Our semi automated build process would need reworking to support multiple bundle ids and stuff

Option 2 on the other hand presents itself with problems too:

  • You can only have test or production apps on a single device at any one time. This implies we would need to get more devices to test from

  • There is a risk of releasing an app pointing to test environments to our production users.

I guess a 3rd option would be to have the ability to reconfigure the app to use either environment (by way of a hidden dev menu or something). This concerns us in regards to caching settings but maybe that could be worked around. I guess it also means we could only run one version of the app on a device at any one time.

Anyway, this is quite an open question for advice. I am really keen to hear what other people are doing when it comes to testing apps. I have read up a bit on this and spoken to a number of people to get input (which is what leads me to the above two options) but would appreciate more input and advice. How do you solve this problem? Maybe I am just approaching this from the completely wrong angle!

Cucumber tags are not being recognised

I have a silly and strange problem. I have taken over a test suite from a colleague which is BDD-Cucumber-ruby based. There are few tags on top of the feature file, which work.

@webview
Feature:
  As a product owner
  I want to blah blah
  So that blah blah

  1. If I add a tag on top of the scenario, its not recognised.

    @runagain

    Scenario: Sign in

    Given..

    When ..

    Then..

and when I run..

D:\application\tests\cucumber>cucumber -p default -t @runagain
Using the default profile...
0 scenarios
0 steps
0m0.003s

This is the silliest of the queries I've posted. But this is bugging me and may be someone can help point me to the simple change I need to do/ a mistake to undo.

Attribute defined test data with Nunit, AutoFixture, NSubstitute and AutoSubstituteDataAttribute

I like the option to define tests using attributes. However, I must be doing something wrong. I have installed the packages:

<packages>
  <package id="AutoFixture" version="3.46.0" targetFramework="net451" />
  <package id="AutoFixture.AutoNSubstitute" version="3.46.0" targetFramework="net451" />
  <package id="AutoFixture.NUnit3" version="3.46.0" targetFramework="net451" />
  <package id="NSubstitute" version="1.10.0.0" targetFramework="net451" />
  <package id="NUnit" version="3.2.1" targetFramework="net451" />
</packages>

Single substituted parameters go through:

[Theory, AutoSubstituteData]
public void Test_Single([Substitute] Service svc)
{
     // executed, shown as success
}

While mixing substitution and some other values fails:

[Theory, AutoSubstituteData]
public void Test_Mixed(int version, string name, [Substitute] IService svc)
{
     // not executed, shown as inconclusive
}

The test output says:

NUnit Adapter 3.0.10.0: Test execution complete

Test adapter sent back a result for an unknown test case. Ignoring result for 'Test_Mixed(150,"name04f0cd50-e89f-4a8f-db6-dab69b58e98e",Castle.Proxies.IServiceProxy)'.

How do I get this to work in VS2015 or in general with NUnit 3x?

The toggle button with on and off have same object or property in Testcomplete, How can i test this feature

I am new to Test complete i am working on a windows application, i have one issue, that not able to test the feature. The toggle button with on and off have same object or property, How can i test this feature.Can i get the text of ON or off button.Please help me.Thanks

Choosing Web Automation Stack

I found it over a few references that it is recommended to go with the same stack for creating automation suite that is being used for the development of the application, i.e., using Java for writing tests if application is Java based.

Is there any specific reason for the same? Or is there any specific hindrance if not followed.

Xamarin Test Cloud

I'm beginner in Xamarin Test Cloud.

I want to write tests for Xamarin Test Cloud.

I have Xamarin UITests in my solution

I tried to launch Repl

  [Test]
public void TestLaunch()
{

    app.Repl();
}

But UITest REPL window didn't open.

Where is error?

Android Studio 2.2: Select device not possible

Since the update to Android Studio 2.2 I am not able to choose the device for each time I run the project.

Android Studio is not asking me on which device I would like to run the app.

I have not set 'Use same device for future launches' enter image description here

Are there more hidden options for that task?

SQL query for inserting data into new colum

I created a new column in a table called emp , by default the new column has all null value .. now i want to copy data of an existing column ,say DEPT_NO present in same table and insert into the newly created column .. what should be the SQL qquery ?

Is any performance testing tools for testing website on mobile browser?

Only I have got Mobiltest on google, but that is working only in wifi, I want to test our website performance in mobile browser in 3G & 2G as well

How I can Test my Spring MVC app?

I use Spring MVC + Spring Security + Spring Data+Spring Boot in my web appl. Give me an example how I can test my controllers, please. I am complete newbie in testing. Example controller:

@Controller
@RequestMapping("/user/add")
@ComponentScan("services")
public class AddController extends WebMvcConfigurerAdapter {
    @Autowired
    private Services services;
    @Autowired
    private UtilService utilService;

    private static final Logger logger = Logger.getLogger(AddController.class);

 @RequestMapping("/agenttypeadd")
 public String addAddAgentType(@RequestParam String name ) {
            services.addAgentType(new AgentType(name));
            return "redirect:/main";

    }
}

Parallel Test Execution Jenkins

I have some automated tests that I'm running using Jenkins.

I've Jenkins connected to my GitSwarm which pulls the code from my branch and then exectutes it.

I have installed the "Parallel Test Job Execution Plugin" for Jenkins.

In the plugin I have specified the tests to run in 3 batches

screenshot

Is there anything else I should specify? I didn't think I would have to since I'm connecting to GitSwarm to run the code. The console output seems to state otherwise !

Building in workspace C:\Jenkins\jobs\GIT_DVT\workspace

git.exe rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository git.exe config remote.origin.url http://ift.tt/25xKWhh # timeout=10 Fetching upstream changes from http://ift.tt/25xKWhh git.exe --version # timeout=10 using .gitcredentials to set credentials git.exe config --local credential.username reganc3 # timeout=10 git.exe config --local credential.helper store --file=\"C:\Users\ADMINI~1\AppData\Local\Temp\2\git5891789764540509525.credentials\" # timeout=10 git.exe -c core.askpass=true fetch --tags --progress http://ift.tt/25xKWhh +refs/heads/:refs/remotes/origin/ git.exe config --local --remove-section credential # timeout=10 git.exe rev-parse "origin/Uni_360_1.0^{commit}" # timeout=10 Checking out Revision 08df9a379e14d8a634e4533d962f5919f755ae67 (origin/Uni_360_1.0) git.exe config core.sparsecheckout # timeout=10 git.exe checkout -f 08df9a379e14d8a634e4533d962f5919f755ae67 git.exe rev-list 08df9a379e14d8a634e4533d962f5919f755ae67 # timeout=10 No record available, so executing everything in one place [parameterized-trigger] Current build has no parameters. ERROR: Build aborted. No projects to trigger. Check your configuration! TestNG Reports Processing: START Looking for TestNG results report in workspace using pattern: C:\jenkins\jobs\GIT_DVT\workspace\unisphere360\target\surefire-reports\ Did not find any matching files. Finished: FAILURE

Any help would be greatly appreciated, it does seem like an easy way to have tests running parallel so hopefully its only a small error.

Thanks, Colin.

How to execute sqlite test file?

I downloaded the sqlite3 source file (not amalgamation version) There are test folder and many test files (journal1.test , pager1.test ... etc)

How to execute these test files?

Proper AngularJS app depending on REST api testing?

I'm developing an AngularJS that consumes a Rails API and I'm not sure how to write tests for it. I assume the tests should pass or fail independently or without connection to the API.

I used Protractor to test the UI so far. Could anyone give me some advice?

lundi 30 mai 2016

FactoryGirl How create a instance which is created by association on callback

Consider two models:

class User < ActiveRecord::Base

  has_one :book

  after_create :create_book
end

class Book < ActiveRecord::Base
  belongs_to :user

  validate_uniqueness :user_id
end

Each user can have and can only have one book. Then I have two Factory defined in my specs:

factory :user do
end

factory book do
  user
end

Then here's the question, when I am writing test for Book, I'd like to create a record book1(let's call it) for Book, when I use FactoryGirl.create(:book). It will create an instance of Book and then tries to create the association defined user. After creating the user, the after_create is trigger, and book2 is created for user. Then it tries to bind book1 with user and is blocked by the uniqueness association.

Now I am using book = FactoryGirl.create(:user).book. Is this the best/right way to do that? I think it's note so intuitive, as I am testing Book, I think it would be the best to have book = FactoryGirl.create(:book)

Thanks a lot.

Fortify (SCA) complaining for Cross-Site Scripting

I have a GridView on web form having Columns bound like

 Text='<%# getName(Eval("Table_Name")) %>'

Fortify Source Code Analyzer complains an vulnerability of Cross-Site Scripting on this line. How to fix it or is it ignore-able?

Does Text='<%# AntiXssEncoder.HTMLEncode(Eval("Participants")) %> help as mentioned in another post?

Thanks

Test for play controller with custom application.conf

I trying make simple controller test in play framework

public class AuthTest extends WithServer {

@Test
public void authByLoginErrorForm() {
    Map<String,String> data = new HashMap<>();
    data.put("username", "");
    data.put("password", "");

    Result result = routeAndCall(fakeRequest("POST", "/auth_by_login"), Helpers.DEFAULT_TIMEOUT);
    assertEquals(400, result.status());
}
}

In builds.sbt i set custom conf for test mode. He need for exclude creation db pool connection in test.

javaOptions in Test ++= Seq(
"-Dlogger.file=test/conf/logback.xml",
"-Xms512M",
"-Xmx1536M",
"-XX:MaxPermSize=384M",
"-XX:MaxMetaspaceSize=384M",
"-Dconfig.file=test/conf/application.conf"
)

After test running i getting error:

[error] Test controller.AuthTest.authByLoginErrorForm failed: java.lang.RuntimeException: java.lang.ClassNotFoundException: Routes, took 2.881 sec
[error]     at play.test.Helpers.routeAndCall(Helpers.java:293)
[error]     at controller.AuthTest.authByLoginErrorForm(AuthTest.java:28)
[error]     ...
[error] Caused by: java.lang.ClassNotFoundException: Routes
[error]     at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[error]     at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[error]     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[error]     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[error]     at play.test.Helpers.routeAndCall(Helpers.java:289)
[error]     ... 37 more
[error] Failed: Total 1, Failed 1, Errors 0, Passed 0
[error] Failed tests:
[error]     controller.AuthTest

i copy routes file to test/conf directory (near with) application.conf, but got same error.

How to effectively test and debug program in industry?

Im a student and wonder how real software is built in industry. How developers and software engineers test and debug programs. For me, I use ide in debug mode but it seems like thats the only way i can think of. How people manage to built large scale software ?

Is it possible to have a zero-cost assert() such that code should not have to be modified between debug and release builds?

I've noticed that some code often looks like this:

#ifdef DEBUG
assert(i == 1);
#endif //DEBUG

and that you may have several blocks of these sitting around in your raw code. Having to write out each block is tedious and messy.

Would it be plausible to have a function like this:

auto debug_assert = [](auto expr) { 
 #ifdef DEBUG
 assert(expr);
 #endif //DEBUG
};

or something like this:

#ifdef DEBUG
auto debug_assert = [](bool expr) {
  assert(expr);     
};
#else //DEBUG
void debug_assert(bool expr) {}
#endif //DEBUG

to get a zero-cost assert when the DEBUG flag is not specified? (i.e. it should have the same effect as if it was not put into the code without the lambda running, etc. and be optimized out by the g++/clang compilers).

Pairwise testing: How to create the table from a text file?

I have a question regarding how to create the table for the pairwise testing. For example, if I have a table with a list of words (each line contains a single word).

E.g.text file contains:

red
blood 
animal

How do I create a table of input with all possible combination then? Would it look something like this? It gets the line number of word and creates all possible outputs. I wanna an output something like this:

| 0 1 2
 -----------
  0 | 0 10 11
  1 | 10 0 21
  2 | 11 12 0

Pass values between TestNG tests

Background: I'm executing tests with TestNG and I have a class annotated with @Test that generates a number, or ID if you will, and that same number is the input value of my second test. Is it possible to pass values between TestNG tests?

iOS Background Service

I want to run screen recording code in background so my App captures other apps screen (for Software QA teams). I have it working in Android with Services, but is it possible to do in iOS?

thanks

Selenium Web Driver Test Case

So I was wondering in order to create a test case of making sure a name or button is present on the page, what code would I use on Selenium webdriver?

Say like if I run the test code for login and password and after I login I want to make sure a specific text is present on the web page, what code on selenium webdriver should I use? This is for Selenium Webdriver

Thanks

Checking Dialog in Espresso

I am trying to check if a progress dialog appears on the screen using espresso's following code. However it doesn't find the dialog anyway.

Espresso Code:

    onView(withId(R.id.button_login)).perform(click());
    waitForSeconds(1000);
    onView(withText(R.string.title_login_progress_dialog)).inRoot(isDialog()).check(matches(isDisplayed())); // NOT FINDING THE VISIBLE PROGRESS DIALOG

ProgressDialog Code in Fragment:

 ProgressDialog pDialog;
    private void showProgressDialog() {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setTitle(getString(R.string.title_login_progress_dialog));
        pDialog.setMessage(getString(R.string.description_login_progress_dialog));
        pDialog.setButton(ProgressDialog.BUTTON_POSITIVE, getString(R.string.ok_string), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        pDialog.show();
    }

This is the gradle code for espresso:

    androidTestCompile ('com.android.support:support-annotations:23.4.0')
    androidTestCompile ('com.android.support.test.espresso:espresso-core:2.0') {
//        exclude group: 'com.android.support', module: 'support-annotations'
    }

    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'

Why can't espresso find the progress dialog?

What is use of Unit Tests and UI Tests?

How Unit Tests and UI Tests will helpful to my app. can anyone explain me with example.enter image description hereenter image description here

Calculate Factor unknown

I'm currently trying to add some JUnit teststo my pathdrawing system in order to check if the calculations are right...
Currently I have:

Class to Test(MapRouteDrawer.java):

protected static double[] getCoords(PolynomialSplineFunction curve, double[] index) {
  final double detailLevel = 1.0;//Tweak this value in order to achieve good rendering results
  final double defaultCoordSize = index[index.length - 1];
  final double[] coords = new double[(int)Math.round(detailLevel * defaultCoordSize) + 1];
  final double stepSize = curve.getKnots()[curve.getKnots().length - 1] / coords.length;
  double curValue = 0;
  for (int i = 0; i < coords.length; i ++) {
    coords[i] = curve.value(curValue);//gets y value of specified x value
    curValue += stepSize;
  }
  return coords;
}

protected static double[] getIndex(Point[] points) {
  final double[] index = new double[points.length];
  if(index.length > 0){
    index[0] = 0;
  }
  for (int i = 1; i < points.length; i++) {
    index[i] = index[i - 1] + Math.sqrt(points[i - 1].distance(points[i]));
  }
  return index;
}

TestClass:

private Point[] dummyPoints = new Point[]{new Point(0,0), new Point(100,0), new Point(0,100)};//Some Points for Testing
//This returns a so called index - the squareroot distance between addedn on top of each other
private double[] dummyIndex = MapRouteDrawer.getIndex(dummyPoints);

@Test
public void testCurve(){
  final double[] testYValues = new double[]{20, 40, 90};
  final PolynomialSplineFunction testFunction = new SplineInterpolator().interpolate(dummyIndex, testYValues);//get a Spline-Interpolated curve
  final double[] coords = MapRouteDrawer.getCoords(testFunction, dummyIndex);//Calls the function to test
  final double factor = testFunction.getKnots()[testFunction.getKnots().length - 1] / coords.length;
  assertEquals(testYValues[0] * factor, coords[(int)Math.round(dummyIndex[0])], 1);//Check if the coordinates are equal
  assertEquals(testYValues[1] * factor, coords[(int)Math.round(dummyIndex[1])], 1);
  assertEquals(testYValues[2] * factor, coords[(int)Math.round(dummyIndex[2])], 1);
}

This is working fine, but if you are familiar with JUnit you may notice the delta of 1 which is neccesary in order for this Test to work...
What I'm trying to achieve is this:

@Test
public void testCurve(){
  final double[] testYValues = new double[]{20, 40, 90};
  final PolynomialSplineFunction testFunction = new SplineInterpolator().interpolate(dummyIndex, testYValues);//get a Spline-Interpolated curve
  final double[] coords = MapRouteDrawer.getCoords(testFunction, dummyIndex);//Calls the function to test
  final double factor;//Unknown... should be dynamic, so it does not matter which detail level I chose
  assertEquals(testYValues[0], coords[(int)Math.round(dummyIndex[0])] * stepSize, 0);//Check if the coordinates are equal
  assertEquals(testYValues[1], coords[(int)Math.round(dummyIndex[1])] * stepSize, 0);//e.g. coords[(int)Math.round(dummyIndex[0])] * factor == 20 etc.
  assertEquals(testYValues[2], coords[(int)Math.round(dummyIndex[2])] * stepSize, 0);
}

So that the first value in assertEquals() is 20, 40, 90 etc. and not a weird 21.39587576787686 (or similar) number and the delta is 0 (or 0.01 if there is no other way) and not 1 which I'm currently using

Because I'm using a detail level in my getCoords() method, which should be able to be adjusted without having to change the test, there is a need to make the "factor" in my test related to the coords-size.

How would I calculate the factor in order for the Test to succeed?
Any help is would be very much appreciated

utest and haxe: run one test case many times

This question is about Haxe language. I would like to use utest to run test classes. (http://ift.tt/1cvaGkt) I need to run each test case 1000 times.

code :

for (i in 0...1000)
runner.addCase(ts);
end for

This code raises an exception:

Exception in thread "main" Haxe Exception: invalid duplicated fixture result

Is it possible to run test cases many times using utest in Haxe?

Thank you in advance

best regards.

Robot framework in Eclipse

I followed the steps given in http://ift.tt/1UgwItn.

I am getting the following error console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0. [ ERROR ] Parsing 'C:\Users\rsarveshwar\workspace\RamyaTest\src\test\robotframework\acceptance' failed: Data source does not exist.

I am using Eclipse Mars / Java and trying to run robot framework / keyword driven tests using selenium.

Can you help please?

Comparing feature descriptor test?

I would like to test different descriptors (like SIFT, SURF, ORB, LATCH etc.) in terms of precision-recall and computation time for my image dataset in order to understand which one is more suitable.

There is any pre-built tester in OpenCV for this purpose? Any other alternative or guideline?

How can I use rollback with PostgreSQL while also checking all foreign key constraints?

I am writing an integration test for a web app using PostgreSQL. I want to run my test code and web server inside a single transaction, so that I can efficiently roll back the transaction after the test to save time on the test run. That is, I am sharing the DB connection between the test code and the web server that is under test, so that both are able to see uncommitted results inside the transaction. However, I also need to insert a lot of data as test fixtures into the database, and the schema has foreign key constraints on this data.

Because my data has these foreign key constraints, I receive foreign key errors when I try to insert objects. It seems that I have to COMMIT in order to get prerequisite data to be recognized. I notice that PostgreSQL has a feature SET CONSTRAINTS DEFERRABLE. However, this isn't really what I want I believe, because this will just make it so that the constraints are not checked until the transaction is committed -- which will never happen, as the transaction will always be rolled back after the test run. i.e. this would be functionally the same as disabling foreign key constraints in the system under test.

It seems that I want is some kind of ability to nest transactions, so that I can COMMIT inside the sub-transaction and have the constraints checked there, but still roll back to the previous point and discard that commit. I investigated ROLLBACK TO SAVEPOINT, but the problem with this is that my code doesn't contain any explicit commits. Normally, I just issue statements and they work -- and I suppose they just autocommit. So it's not really clear how I would modify the application code to do an explicit commit. Also, the usage example doesn't show that it can actually be used to revert to a point after COMMIT was used. The example just shows a use of INSERT without a COMMIT, so I'm not sure if this actually works for my purposes.

Testing the Response code of a WebService without a running server

I would like to test my WebService with JUnit (EasyMock and Hamcrest) without having to start my server (Wildfly)

private RegisterUserWebService testeee = new RegisterUserWebService();

@Test
  public void test() {


    Response response = testee.registerUser();
    verifyAll();
    assertThat(response.getStatusInfo().getStatusCode(), equalTo(Status.CONFLICT));

  }

I am getting a ClassNotFoundException:

java.lang.RuntimeException: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl
            at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:152)
            at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:120)
            at javax.ws.rs.core.Response$ResponseBuilder.newInstance(Response.java:848)
            at javax.ws.rs.core.Response.status(Response.java:590)
            at javax.ws.rs.core.Response.status(Response.java:601)
            at my.package.webservices.RegisterUserWebService.registerUser(RegisterUserWebService.java:50)

As I understand it, no implementation could be found for javax.ws.rs.core.Response, and the default one seems to be the glassfish one which I don't have, hence the ClassNotFoundException.

How could I tell my test to use the Response from Wildfly ? Or is there another way ?

How to set name which is unique for a component based on thier properties?

I want to differentiate each component in my application uniquely.So how can i prepare an unique name with its properties so that i can set this name. In my testing tool i have to perform action on the correct component. I tried name preparing like

String parentName = component.getParent();
String xpoint = component.getX();
String ypoint = component.getY();
component.setName(parentName_xpoint_ypoint);

Can you tell me whatever i tried will give the unique component if i call using
component.getName().equals(parentName_xpoint_ypoint) ?

dimanche 29 mai 2016

Testing multiple login and check validation for wrong login credential

Scenario is:I have 3 records of username and password stored in excel sheet1.I want to test login with each record one by one without dataprovider and using POM.Here is my frame work design:generic method in one package where read from Excel method is defined.One more package by name TestConfiguration where all pre and post condition are defined(browser openening,maximize etc.).Now in pagerepo package i created one login method.Now in regression page iam creating object for login page to execute and this class extend test configuration.Now tell wr to put logic for aboce scenario.Thanks

How to functional/unit test file download in Javascript NodeJS-ExpressJS

In my NodeJS ExpressJS application, I have an API that I consume to convert to a CSV file and subsequently download it on the client like so:

res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=BuyNowOrders.csv;');
res.end(csv, 'binary');

I have Mocha/Sinon/NighwatchJS test suite that I use for unit testing as well as functional testing with a full-fledged mock-api server module that serves up mock data.

My question is - how do I test this functionality? Normally I do functional testing testing and unit testing for each module.

I have so far written tests for the Download button to be present on the page, but am not sure how to test whether the file has been downloaded.

websockets stress (load) test (node.js)

I have an node.js application based on websockets. I need to do load test for this application. There are three basic points which need to be tested: 1. websocket clients connect to server and server sends back success/error connection message with a little help data (json). 2. Every 1/2 seconds each connected client pings server and server sends response to client. 3. There is also a manager client who broadcasts messages to all connected clients. For these points I need to check latency of messages send/receive. For third point also need to check delay between each client message receive.

I am using http://ift.tt/1AM8BIF node.js module , websocket server implemented on node.js native cluster module. Broadcasting done by simple foreach through connected clients in each forked worker. Also I need to know apx. how many clients can handle my server. So I want to understand is there any test modules/tools that can help me to achieve my goal . Thanks.

EmberJS - the run loop is cleared with "asyn/await" instead of the use of "then"

I have a strange behavior with run loop in a test (yes, for everybody is difficult ;-) ) and with the babel plugin async to generator transform.

First, I have "an old school code":

await Ember.run(function() {
  return task.save().then(() => {
    subtask_1 = task.create_subtask();
    return subtask_1.save();
  }).then(() => {
    subtask_2 = task.create_subtask();
    return subtask_2.save();
  }).then(() => {
    subtask_3 = task.create_subtask();
    return subtask_3.save();
  }).then(() => {
    subtask_4 = task.create_subtask();
    return subtask_4.save();
  }).then(() => {
    return subtask_4.promise_priorize_before(subtask_2);
  });
});

It works. ;-)

But, if I tried, I think the equivalent code with the "new way", I have an error:

await Ember.run(async function() {
  console.log(Ember.run.currentRunLoop);
  await task.save();
  console.log(Ember.run.currentRunLoop);

  subtask_1 = task.create_subtask();
  console.log(Ember.run.currentRunLoop);
  await subtask_1.save();
  console.log(Ember.run.currentRunLoop); // <---- null here

  subtask_2 = task.create_subtask();     // <---- crash here
  console.log(Ember.run.currentRunLoop);
  await subtask_2.save();

  subtask_3 = task.create_subtask();
  await subtask_3.save();

  subtask_4 = task.create_subtask();
  await subtask_4.save();

  return subtask_4.promise_priorize_before(subtask_2);
});

I don't understand why, but the current run loop is cleared after a simple "save" of Ember data.

The error is "Assertion Failed: You have turned on testing mode,… any code with asynchronous side-effects in a run" because Ember.run.currentRunLoop is null.

Have you an idea?

Frédéric

samedi 28 mai 2016

Play+Scala suite test not found type PlaySpecification

It is my first web app using Play Framework and Scala. I am following this tutorial > http://ift.tt/1MZQztl and after the app working well, my tests cannot work. When I type sbt test the compiler says cannot find PlaySpecification.

[error] /home/felipe/Documentos/AMC/amc-project/play-scala-library/test/controllers/HomeControllerIntegrationSpec.scala:6: not found: type PlaySpecification
[error] class HomeControllerIntegrationSpec extends PlaySpecification {

These are my dependencies >

libraryDependencies ++= Seq(
  jdbc,
  cache,
  ws,
  evolutions,
  "com.typesafe.play" %% "anorm" % "2.4.0",
  "commons-codec" % "commons-codec" % "1.6",
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test
)

resolvers += "scalaz-bintray" at "http://ift.tt/1s6xCLk"

SQLiteDatabse unitTest

I have a problem with SQLDatabase testing.

Here some parts of my code, I skip unimportant parts of code like TetsObject declaration (contain 2 fields: String id and String Title) and definition of database table and its fields.

build.gradle:

android {
    ...
    testOptions { unitTests.returnDefaultValues = true }
}

dependencies { testCompile 'junit:junit:4.12' }

DatabaseHelper:

public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database.db";
private static final String TABLE_TABLE_CREATE = "...";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TABLE_TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ... } }

TableOperations:

public class TableOperations {
private SQLiteDatabase mDatabase;

public TableOperations(SQLiteDatabase database) {
    mDatabase = database;
}

public List<TestObject> getEnteries() { ... }
public TestObject getEntery(String id) { ... }
public void addEntery(TestObject object) { ... }
public void updateEntery(String id, TestObject object) { ... } }

Test:

public class ExampleUnitTest extends AndroidTestCase {
private SQLiteOpenHelper mDatabaseHelper;

@Override
protected void setUp() throws Exception {
    super.setUp();

    Context context =new RenamingDelegatingContext(getContext(), "test_");
    mDatabaseHelper = new DatabaseHelper(context);
}

@Override
protected void tearDown() throws Exception {
    super.tearDown();

    mDatabaseHelper.close();
}

@Test
public void testDatabaseNotNull() throws Exception {
    assertNotNull("Database is null", mDatabaseHelper.getWritableDatabase());
}

@Test 
public void testDatabaseReading() throws Exception{
    // insert some data to database
    TableOperations operations = new TableOperations(mDatabaseHelper.getWritableDatabase());
    // assertEquals test database reading here
} }

I want to test database operations but can't because firs test always failed, mDatabase always null.

Java NullPointerException when doing a test from an arrayList [duplicate]

This question already has an answer here:

I wanna test the method DrawCard() from the class ModelPlayer that takes the first not-null Color value from the arrayList PoliticCards of the class PoliticCard and puts it in the arrayList politicCards of the class Player; and i get two NullPointerExceptions.

public enum Color {
    BLACK, PURPLE
}
public class PoliticCard {
    private static ArrayList<Color> politicCards;
    public PoliticCard(){
        setPoliticCards(new ArrayList<Color>());
        int i=0;
        while (i<13){//adds 13 Color values set to BLACK
            politicCards.add(Color.BLACK);
            i++;
        }
        while (i<26){//adds 13 Color values set to PURPLE
            politicCards.add(Color.PURPLE);
            i++;
        }
        }
        Collections.shuffle(politicCards);

    }
    public static ArrayList<Color> getPoliticCards() {
        return politicCards;
    }
    public static void setPoliticCards(ArrayList<Color> politicCards) {
        PoliticCard.politicCards = politicCards;
    }


}
public class Player {
    private int id;//id of the player, goes from 1 to 10
    private ArrayList<Color> politicCards;
    public Player(int id){
        this.setId(id);
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public ArrayList<Color> getPoliticCards() {
        return politicCards;
    }
    public void setPoliticCards(ArrayList<Color> politicCards) {
        this.politicCards = politicCards;
    }
public class ModelPlayer {

    public void DrawPoliticCard(Player player){
        int i=0;
        if(PoliticCard.getPoliticCards().get(i)!=null){
                player.getPoliticCards().add(PoliticCard.getPoliticCards().get(i));//This
// is the line where i get the first NullPointerException
            PoliticCard.getPoliticCards().remove(i);
        }else{
            i++;
            player.getPoliticCards().add(PoliticCard.getPoliticCards().get(i));
            PoliticCard.getPoliticCards().remove(i);
        }

        }



}
public class ModelPlayerTest {

    @Test
    public void testDrawCard() {
        Player player = new Player(1);
        ModelPlayer modelPlayer = new ModelPlayer();
        player.setPoliticCards(null);
        new PoliticCard();
        modelPlayer.DrawPoliticCard(player);//This is the second line where i get NullPointerException
        assertNotNull(player.getPoliticCards().get(0));
    }

}

What is travis-ci ,software build ,tests?

I recently was learning various tools to get started to open source contribution. I found this tool called travis-ci which said that its used for testing,now i am further confused that what is testing(how and when it is done). Another thing is build,what is software building ,is it like compiling the code?,and when and where is the software building in an open source contribution process.Please someone clear these topics because these are delaying me in getting started for open source contribution.

Phoenix Framework: What's the correct way to seed database for testing?

I am building my first Phoenix app and am trying to write a test that will verify that the user retrieved from a JWT in a connection's Authentication header is the correct user, is authenticated, etc.

What is the correct way to seed the database with a single record for this test?

Should it be done:

  • globally, using the test/test_helper.exs file, by requiring priv/repo/seeds.exs and executing manual Ecto operations

OR

  • per test (in which case I am not certain how best to proceed)

Finally, what is the correct way to clean out the test database after successfully running my tests, so I can avoid trying to create the same record every time I run a test?

vendredi 27 mai 2016

PG::UndefindColumn: ERROR on only at action test

I'm getting this test error when I run my test by "bundle exec rake test"

ERROR["test_unsuccessful_edit", UsersEditTest... ActionView::Template::Error: ActionView::Template::Error: PG::UndefinedColumn: ERROR: column groups_users.group_id does not exist

It works fine on development. My test script is below.

# test "unsuccessful edit" do
#   log_in_as(@user)
#   get edit_user_path(@user)
#   assert_template 'users/edit'
#   patch user_path(@user), user: { name: "",
#   email: "foo@invalid",
#   password: "foo",
#   password_confirmation: "bar",
#  }
#   assert_template 'users/edit'
# end

As you can see, I spiked this test since it apparently nothing wrong in the development environment.

The error message is saying "group_id" column does not exist in table "groups_users". But it's actually exist since I've run migration and checked database/behavior by hands.

Is there any way to make this test script work?

In my models, as you may be guessing, I have below relationships method.

• User.rb

  has_and_belongs_to_many :groups, join_table: :groups_users, dependent: :destroy

• Group.rb

  has_and_belongs_to_many :user, join_table: :groups_users

And my migration file looks like this:

class GroupsUsers < ActiveRecord::Migration
  def change
    create_table :groups_users, :id => false do |t|
        t.integer :group_id
        t.integer :user_id
    end
  end
end

There is no validation for these groups values to be present. Please let me know if you have any idea or questions.

Thanks,

'class' object has no attribute 'method'

I'm getting an error "AttributeError: 'Test Employee' object has no attribute 'increment_salary'". Not sure why I'm getting this error because 'increment_salary' is a method, not an attribute and I'm 99% sure I created it correctly. I've searched and the only answers I saw said to check mix of indentation and spaces so I went through and triple checked every indent. It may be wrong here because I am not familiar with how to copy code here but I am sure I did it right in geany.

import unittest

class Employee():
    """stores and updates info for each employee"""
    def __init__(self, first_name, last_name, salary):
        self.first_name = first_name
        self.last_name = last_name
        self.salary = salary
    def update_salary(self, new_salary):
        self.salary = new_salary
    def increment_salary(self, increase):
        self.salary += increase

class TestEmployee(unittest.TestCase):

    def setUp(self):
        first_name = 'first'
        last_name = 'last'
        pay_name = 100
        self.employee = Employee(first_name, last_name, pay)

    def test_update_salary(self):
        new_salary = 110
        self.employee.update_salary(self.new_salary)
        self.assertEqual(self.new_salary, self.update_salary)

    def test_raise(self):
        increase = 10
        self.employee.increment_salary(increase)
        self.assertEqual(110, self.increment_salary(increase))

unittest.main()

How to send an accessibility event from a Junit test and receive the AccessibilityEvent in the same test Android

I need to send an accessibility event from within a Junit test case in Android, or at least an Android test case, and receive it in an onAccessibilityEvent method in the same test class. My app works by receiving accessibility events from other apps, much like talkback, but, for the test cases, I also need to generate the accessibility events so that I don't need to run third party apps over and over to test. I can call my own onAccessibilityEvent method from within a test case, and that works, but when I create my own events, I cannot edit their fields because they are unsealed and throw an exception.

Cassandra CQL syntax tests

I'm trying to create a thin parser-generator for Cassandra CQL. The goal is to alter statements with custom syntax (i.e. extended CQL) into valid CQL statements. The Cassandra is an open source project, and I expected to find list of all test statements. Could you give a hint on how to find the CQL test statements?

Load test WebClient server

I am a developer who has no load test experience and would like to learn how to do this.

I have a simple client server application where the client sends a request to the server and the server sends a response back.

I would like to load test this but I am not sure how to do this. Here is my GetResponse method which receives a response from the server.

    Response GetResponse(Request request)
    {
        string data = Newtonsoft.Json.JsonConvert.SerializeObject(request);

        System.Net.WebClient wb = new System.Net.WebClient();
        string response = wb.UploadString("http://localhost:8080", data);

        return Newtonsoft.Json.JsonConvert.DeserializeObject<Response>(response);
    }

My initial thoughts are to write a routine to send a load of get response requests all at the same time and then try and monitor the CPU ticks or other to see how it is performing.

Can anyone let me know if this is the correct way to go about it? I am also not really sure what the best stats to gather are?

Thanks in advance

If I have an SBT multi-project build, how can I make A's test dependencies not leak in to B's tests

So, I have an SBT project with modules A and B.

  • A depends on B.
  • A and B's normal project packages are compatible.
  • A has a package for testing that is incompatible with a package that B uses for tests.
  • A does not depend on B's test packages
  • A's tests fail, because of the test package incompatibility

In my eyes, this failure is invalid, because A's tests do not depend on B's tests.

I'm using

A.dependsOn(B % "compile->compile;test->compile")

meaning

  • A's compile depends on B's compile
  • A's test depends on B's compile.

Am I doing something wrong?

Here's the actual build file. Relevant project is doobieSupport23 depending on core

Here's the build error. You can see that it's pulling in scalaz 7.2 in the build, but it should only be pulling scalaz 7.1.6

sinon stub with es6-promisified object

Ok my setup is as follows: Using node 6.2, es6-promisify, sinon, sinon-as-promised, and babel to transpile support for es6 import/export.

My code under test looks something like this:

const client = restify.createJsonClient({
    url: 'http://www.example.com'
});
export let get = promisify(client.get, {thisArg: client, multiArgs: true});

export default function* () {
    yield get('/some/path');
}

And then in my test file I have something like this:

import * as m from mymodule;
it('should fail', function(done) {
    let stub = sinon.stub(m, 'get').rejects('i failed');
    client.get('/endpoint/that/leads/to/mymodule/call', function(err, req, res, data) {
        stub.called.should.be.eql(true); // assertion fails!!
        done();
    }
});

I've also tried stubbing the original client.get call, and that doesn't work either. The only thing I've gotten to work is promisifying on the fly with each call, and stubbing the original client.get, which seems pretty lame. E.g.:

export const client = restify.createJsonClient({
    url: 'http://www.example.com'
});
function get() {
    return promisify(client.get, {thisArg: client, multiArgs: true});
}

export default function* () {
    yield get('/some/path');
}

And test code doing this:

import {module_client} from mymodule;
it('should fail', function(done) {
    let stub = sinon.stub(module_client, 'get').yields('i failed');
    client.get('/endpoint/that/leads/to/mymodule/call', function(err, req, res, data) {
        stub.called.should.be.eql(true); // assertion succeeds
        done();
    }
});

And so the question, if it's not completely obvious, is why does my original code not work? And is there a way to make the stub work without promisifying the original restify each time (e.g. how do other people get this sort of thing working)?

NodeJS - Testing an API with Request and Promise

I'm not an Javascript expert, and I failed to understand how to work some Js particularity.

I wanted to automated test, I dit it, it works. The algorithm is simple :

[for each] test [do] request() [then] testRequest().

function requestFunction(url, KeyWord, path, expected){

    request( url + path + '/', function (error, response, body) {

    if (!error && response.statusCode == expected) {
        msgSuccess("["+KeyWord + "] :\t\tok\t(" + expected + ')' );
    }else{
        msgError("["+KeyWord + "]\t\tERROR => " + error);
        msgError("Error result: \n" + body);
    }
});

But I want to split the test part, from the request, and manage it with promise:

var promise1 = new Promise(requestFunction(url, KeyWord, path, expected));
var promise2 = new Promise(testRequest(error, response, body, expected));

Promise.all([promise1, promise2]).then(
    console.log(KeyWord + " ok"),
    showOnlyTheError(allErrors));

But I have no idea how to get and give the testRequestResult() parameters (error, response, body)

The other point is that I'm pretty sure that all the reject will be concatenated and the result will automatically goes to the allErrors variable.

eg: testRequest(...){ reject("[Error]" + **ErrorNumbers** + ", ")};

Will at the end show "1, 2, 3,".

But I can't explain why, and especially how?

Thanks in advance.

how to test a golang library that takes an executable using itself as an argument?

I am writing a library with methods that you can use to write a server executable and a client executable. I am also writing a "main" package that uses the library to implement those executables.

My simplest question is, how do people normally write tests for golang executables? A main_test.go or similar seems to be non-existant in the handful of other people's packages I looked at.

I'm also in the perhaps unusual situation where my server code internally needs to run instances of (one type of) the client (my server spawns clients). So my server library method that does all the server work (listen for connections from clients and respond to them) needs* to take the name of (path to) the client executable as an argument. But of course, while testing this library code I don't have an installed client executable. How do I test in this situation?

In particular, I am using go's built-in tools for testing, ie. go test ./my_library.

[*] or is there an alternative way of structuring things?

Is there something like a jasmine `toNotContain` acceptance criteria for tests?

Jasmin comes with many functions for checking the expected values for validating specifications and tests.

Is there besides

getJasmineRequireObj().toContain = function() { ... };

somthing like a

getJasmineRequireObj().toNotContain = function() { ... };

?

If not, how to add an extension or plugin to deliver this feature also to our community of developers?

How to test Meteor.users with Mocha

I have a function as follows:

if(Meteor.isServer) {
Meteor.methods({
    addUser: function (newUser) {
        check(newUser, { email: String, password: String });
        userId = Accounts.createUser(newUser);
        return userId;
    },
    getUser: function (userID) {
        check(userID, String);
        return Meteor.users.find({_id: userID}).fetch();
    }
});

And I am trying to test this function using Mocha:

if (Meteor.isServer) {
let testUser;
describe('Users', () => {
    it("Add User", (done) => {

        testUser = {email: 'test@test.test', password: 'test'};

        try {
            testUser._id = Meteor.call('addUser', testUser);
            console.log(Accounts.users.find({_id: testUser._id}).fetch());
            done();
        } catch (err) {
            assert.fail();
        }
    });

    it("Get user", (done) => {
        try {
            Meteor.call('getUser', testUser._id);
            done();
        } catch (err) {
            assert.fail();
        }
    });
});

And I know that the meteor call with 'addUser' works, because the console.log after that returns the user that I just made and the first test passes when I run it with "meteor test --driver-package practicalmeteor:mocha"

But then I come to the second testing part, where I try to get the user with the meteor call 'getUser', but then I get stuck:

'Cannot call method 'find' of undefined'

Now I know that the difference is that I use 'Meteor.users' instead of 'Account.users' to find the user, but I am totally in the dark what the difference is between these two. Should I replace all the Meteor.users method calls with Accounts.user method calls or not? How would you test this?

Node.js sinon stubbing a function in parallel executions causes failed tests

I have 2 test cases which test the same function just taking 2 different executions paths, so to illustrate:

MyClass.prototype.functionBeingTested = function() {
    if (this.check1()) {
        this.isCheck1Called = true;
    } else if (this.check2()) {
        this.isCheck1Called = false;
    } else {
        ...
    }
};

My 2 test cases are as follow:

it('should take check1() execution path', function() {
    var myClass= new MyClass({}, {}, {});
    var check1Stub sinon.stub(MyClass.prototype, 'check1');
    check1Stub.returns(true);
    myClass.functionBeingTested();
    myClass.isCheck1Called.should.equal(true);
});

it('should take check2() execution path', function() {
    var myClass= new MyClass({}, {}, {});
    var check2Stub sinon.stub(MyClass.prototype, 'check2');
    check2Stub.returns(true);
    myClass.functionBeingTested();
    myClass.isCheck1Called.should.equal(false);
});

Now by default, check1() returns false so I don't stub it in the second test case, but by the time the second case is running, the check1() function stub is still active and causes the second case to enter the execution path of the first case as-well, making the second case test fail.

I understand it's a problem of test running in parallel and the first sinon stub still being used by the first test case, is there anyway I can solve this problem?

Python based mqtt device simulator required

I am looking towards a pure python based tool for mqtt device simulator. Can anyone suggest me one.

I used to work in a SNMP project where we used sourceforge's SNMP simulator and net-snmp text based tool for valdaion. Can anyone suggest me a similar tools ?

How can i test my symfony Application

After more than 15 days i have finished developing my new symfony application , now I wanted to test it , and I kinda lost concerning. So my questions for you php GEEK are the following :

1- What are the frameworks that i can use to test my php app?

2- can someone specify step by step how can I manage to test my app?

3- What kind of test could I made other than the Unit test?

4- How can I made the unit test step by step please (separating the database and the external ressources...), in another word what is the correct way to use integration tests in my build process?

Thnak you in advance.

Jmeter: Response data is not loaded completly

I'm trying to test a web page.for few request response data is not getting loaded completely, I can see only first few parts of a page. Where as for few request its working fine.Can anyone help me in this?

jeudi 26 mai 2016

mocha/chai testing as meteor package test: how to get dom elements or variable values

I'm writing my first test package for my meteor app with mocha. So I run a package test by doing meteor test-packages --driver-package practicalmeteor:mocha my:package.

package.js

Package.onTest(function(api) {
    api.use([
        'templating', 
        'ecmascript'
    ]);
    api.use('practicalmeteor:mocha');

    api.addFiles('tests/client.js', ['client']);
});

client.js

import { chai, expect, should } from 'meteor/practicalmeteor:chai';
chai.should();

describe('First module', function (done) {

    it("All needed elements existing", function(){
        should.exist($('#example'));    // doesn't work 
        expect($('#example'), 'example element').to.not.be.undefined;   // doesn't work either
    });
});

template

<template name="example">
    
        <h1>Restricted area</h1>
    
        <div id="#example">
            
                <p>is set</p>
            
                <p>is missing</p>
            
        </div>
    
</template>

helper

Template.example.helpers({
    session: function() {
        return !!(Session.get('anything'));
    }
})

So how would I test this very basic example. For me there are three problems:

  1. Do I have to take care of the alaning:roles thing?
  2. First I would check if dom elements are existing. But that doesn't work. Is that possible in a package test? Or is it a wrong thinking of mine?
  3. How can I test the Session-var?

Maybe I have a complete misunderstanding of doing a test, so I would appreciate any example how you would test this basic example. I've read tutorials for hours, but still have some problems to get started.

Mockito not working on update/create in RESTcontroller

I'm trying to write some tests using Mockito and I managed to write them for findAll and delete operations but for the create and update, they won't work.

@RunWith(MockitoJUnitRunner.class)
public class RentedControllerTest {

    @Mock
    private RentedService rentalService;

    @Mock
    private MovieService movieService;

    @Mock
    private ClientService clientService;

    @InjectMocks
    private RentedController rentalController;

    @InjectMocks
    private MovieController movieController;

    @InjectMocks
    private ClientController clientController;


    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Test
    public void getMovies() throws Exception {
        List<Movie> movies = new ArrayList<>();
        movies.add(mock(Movie.class));
//        System.out.println(movies.toString());
        when(movieService.findAll()).thenReturn(movies);
////        System.out.println(movieService.findAll().toString());
        MoviesDto response = movieController.getMovies();
        assertEquals("should be 1 movie", 1, response.getMovies().size());
    }

    @Test
    public void updateMovie() throws Exception {
        Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
        MovieDto movieDto = mock(MovieDto.class);
        System.out.println(movie.toString());
        when(movieService.updateMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
//        Movie m = new Movie();
//        m = movieService.updateMovie(2,"Lotrrrrr",0, "dir2", 2003);
//        System.out.println(m.toString());
        Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
        System.out.println(map.toString());
        assertEquals("Title should be Lots", "Lotr", map.get("movie").getName());
    }

    @Test
    public void createMovie() throws Exception {
        Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
        MovieDto movieDto = mock(MovieDto.class);
        when(movieService.createMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
        Map<String, MovieDto> map = movieController.createMovie(movieDto);
        assertEquals("Title should be Lotr", "Lotr", map.get("movie").getName());
    }

    @Test
    public void deleteMovie() throws Exception {
        ResponseEntity response = movieController.deleteMovie(1);
        assertEquals("Http status should be OK", HttpStatus.OK, response.getStatusCode());
    }
}

So the line "when(movieService.update....) work's just fine. I tested it with the write lines as you can see in the code and it works. The problem is here

Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);

I gives me NullPointerException inside that method. The method looks like this:

@RequestMapping(value = "/movies/{movieId}", method = RequestMethod.PUT, consumes = CatalogMediaType.API_JSON)
    public Map<String, MovieDto> updateMovie(@PathVariable final Integer movieId,
                                             @RequestBody final MovieDto movieDto) {
        log.trace("updateMovie: movieId={} movieDto={}", movieId, movieDto);

        Movie movie = movieService.updateMovie(movieId, movieDto.getMovie().getName(), movieDto.getMovie().getNumberofrentals(), movieDto.getMovie().getDirector(), movieDto.getMovie().getYear());

        Map<String, MovieDto> movieDtoMap = new HashMap<>();
        movieDtoMap.put("movie", new MovieDto(movie));
        log.trace("updateMovie: movieDtoMap={}", movieDtoMap);

        return movieDtoMap;
    }

The application itself works perfectly, the problem arises only when runing the mockito tests.

java.lang.NullPointerException
    at ro.ubb.stcatalog.web.controller.MovieController.updateMovie(MovieController.java:41)
    at ro.ubb.stcatalog.web.controller.RentedControllerTest.updateMovie(RentedControllerTest.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    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:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

2016-05-26T23:51:52,845 TRACE [main]: MovieController                      - createMovie: moviesDto=Mock for MovieDto, hashCode: 825249556 

java.lang.NullPointerException
    at ro.ubb.stcatalog.web.controller.MovieController.createMovie(MovieController.java:54)
    at ro.ubb.stcatalog.web.controller.RentedControllerTest.createMovie(RentedControllerTest.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    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:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

I don't really understand what the problem is if the findAll and delete work just fine... Any ideas?

Pytest Ignore Parent Tests

I am writing some tests against a series of objects that all part of a large inheritance tree.

class A(object):
    # stuff

class B(A):
    # more stuff

class C(B):
    # even more stuff

I am writing tests in pytest, and it makes sense to copy the same tree within my test classes. To continue with the example.

class TestA(unittest.TestCase):
    setUp(self):
        # some prep

    def test_a(self):
        # a test for A

class TestB(TestA):
    setUp(self):
        super(TestB, self).setUp()

    def test_b(self):
        # a test for B

class TestC(TestB):
    setUp(self):
        super(TestC, self).setUp()

    def test_c(self):
        # a test for C

Everything is running great, except I am wondering if it is possible to have pytest ignore running tests that are inherited from parent classes. For example, when TestC is run, it runs test_a, test_b, and test_c. test_a, and test_b are already being discovered and tested for the class TestB and TestA, so I'd like to remove some unnecessary testing time.

Mockito test throws NullPointerException for no reason [duplicate]

This question already has an answer here:

I'm trying to write some tests in Mockito but for some reason it fails at some point:

@RunWith(MockitoJUnitRunner.class)
public class RentedControllerTest {

    @Mock
    private RentedService rentalService;
    private MovieService movieService;
    private ClientService clientService;

    @InjectMocks
    private RentedController rentalController;
    private MovieController movieController;
    private ClientController clientController;


    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Test
    public void getMovies() throws Exception {
        List<Movie> movies = new ArrayList<>();
        movies.add(mock(Movie.class));
//        System.out.println(movies.toString());
        when(movieService.findAll()).thenReturn(movies);
//        System.out.println(movieService.findAll().toString());
//        MoviesDto response = movieController.getMovies();
//        assertEquals("should be 1 movie", 1, response.getMovies().size());
    }

It failes at "when..." It throws NullPointerException but it doesn't say anything more. No explanation. The system print from before shows 1 mock in my list, what is happening?

EDIT: The problem was that I added the @Mock and @InjectMocks only for the first Services/Controllers.

Protractor tests inconsistently passing / failing

The problem that I have with this test is that sometimes it passes, sometimes it fails, and when it does the latter a "Failed: No element found using locator: By(css selector, .add.create_ServiceOrders)" message appears in the console. Idk what to do to fix it :(

 describe('angularjs homepage', function() {

   it('should greet the named user', function() {     
  //browser.ignoreSynchronization = true
  browser.get('http://ift.tt/1TE7G9U');
  browser.waitForAngular();

  var input = element(by.model('loginInfo.login'));
  input.sendKeys('xxx');
  expect(input.getAttribute('value')).toBe('xxx');

  var input = element(by.model('loginInfo.password'));
  input.sendKeys('yyy');
  expect(input.getAttribute('value')).toBe('yyy');

  browser.waitForAngular(); 

  browser.driver.actions().sendKeys(protractor.Key.ENTER).perform();

  browser.waitForAngular(); 

  var AddButton = element(by.css(".add.create_ServiceOrders" ));
  browser.actions().mouseDown(AddButton).mouseUp().perform();   
  browser.actions().mouseMove(AddButton).click().perform();

  browser.waitForAngular(); 

  var AddButton = element(by.css(".icon-standard-issue-floors" ));
  browser.actions().mouseDown(AddButton).mouseUp().perform();  
  browser.actions().mouseMove(AddButton).click().perform();

  browser.waitForAngular(); 
  .....
 });
});

karma can I mock service but not include it

My test is running into an error saying the following from and angular site

Unknown provider: UserServiceProvider <- UserService <- ResourceService <- taOptions

Error: [$injector:unpr] http://ift.tt/1ZsJvtS$injector/unpr?p0=UserServiceProvider%20%3C-%20User Service%20%3C-%20ResourceService%20%3C-%20taOptions

When I include the service on karma.conf it tells me there are errors on the service.js and is trying to test it. Is there a way for me to mock the service without including it?

I tried it like this but it isn't working:

inject(function(_$injector_) {
  var $controller;
  this.httpBackend = _$injector_.get('$httpBackend');
  this.rootScope = _$injector_.get('$rootScope');
  $controller = _$injector_.get('$controller');
  this.scope = this.rootScope.$new();
  $q = $injector.get('$q');

  this.UserService = {

  };
...

karma trouble with angular constant

I had working tests before a merge of 2 branches. The new branch brought along an angular constant which I believe broke all the tests. I have an angular constant like so

...
return $http.get(ENV+'/api/url').then(function (response) {
                appName.constant("userinfo", response.data);
                userID = response.data.user.id;
            }, function(errorResponse) {...

and my test controller set up like this

beforeEach(function() {
    module('appName');
    return inject(function($injector) {
      //nothing here yet
    });
  });

I was able to shorten the amount of errors by creating this stub for the constant that my tests would use

angular.module('appName').constant('userinfo', {
  user: {
    id: 0
  }
});

window.ENVApp = '/ng-app'

And I am running into this error

Error: [$injector:unpr] http://ift.tt/1ZsJvtS$injector/unpr?p0=httpInterceptorProvider%20%3C-%20httpInterceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile%20%3C-%20ModalService%20%3C-%20taOptions

The files are loaded into karma.conf. Any ideas how to get around this error? My tests wont run because of this issue.

Tool for testing a web application

I am searching for tool for testing my web application (Java EE) by sending http requests and analysing the responses ?

How to test relative dates in PHP

I've got a code snippet like this (PHP 5.3):

  <?php
  $last_sunday = new DateTime();
  $last_sunday->modify("Sunday last week");
  $last_sunday->setTime(0, 0, 0);

  $last_saturday = new DateTime();
  $last_saturday->modify("Saturday last week");
  $last_saturday->setTime(0, 0, 0);

  $next_sunday = new DateTime();
  $next_sunday->modify("Sunday this week");
  $next_sunday->setTime(0, 0, 0);

  $this_saturday = new DateTime();
  $this_saturday->modify("Saturday this week");
  $this_saturday->setTime(0, 0, 0);

What I'd like to figure out is how to test this (a la PHPUnit or some other framework - or even just via manual testing) for what is returned based on the current day of the week. I've noticed interesting behaviors especially around Sundays. I've tried to reset the date on my VM (using a CentOS 6 image on VirtualBox) but that isn't working.

If today is May 26 I can manually test and see that it works. The following print out as values if I print ->format('m-d h:i a'):

05-22 12:00 am // $last_sunday
05-21 12:00 am // $last_saturday
05-29 12:00 am // $next_sunday
05-28 12:00 am // $this_saturday
05-26 11:09 am // this is today

If it isn't clear, I'm simply trying to determine a reliable means for setting the weekend dates before and after (in America where calendar week starts on Sunday). Thanks for any suggestions.