lundi 31 août 2015

Angular JS testing with external libray like Google Analytics

How do you testing angular controller with external library usage such as google analytic event tracking. For example:

$scope.showVolumn  = function() {
  ga('send', {
    'hitType': 'event',          
    'eventCategory': 'Volume',   
    'eventAction': 'click',      
    'eventLabel': 'Interaction'
  });

  if($scope.native !== 'true')
    vm.showVolumnCtl = !vm.showVolumnCtl;
};

Run thought my test code this error appeard

ReferenceError: Can't find variable: ga

I don't think you can inject ga in the beforeEach right? Any solution i can overcome this?

Unable to do unit testing for an API in sequelize using Mocha and Chai

Hi I am new to unit testing. I am currently working on Mocha,Chai and Sequelize to make a TDD unit test for an API. But while running the unit test using Mocha, I get the following error:

 msg: 'TypeError: Cannot read property \'firstName\' of undefined' } to not exist

The unit test I have written for my API is as follows:

describe('createUser', function () {
it('should create a User', function (done) {
    var email_Id = "xyz@gmail.com";
    var firstName = "xyx";
    var values = JSON.stringify({
        body: {
            email_Id: email_Id,
            firstName: firstName
        }
    });
    user.createUser(values, function (err, response) {
        expect(response).should.be.an(object);
        expect(err).to.be.null;
    });
    done();
   });
});

My API is as follows:

createUser: function (req, res) {
    var param = req.body;
    var firstName = param.firstName;
    var email_Id = param.email_Id;
    db.sequelize.sync().then(function () {
        user.create(param).then(function (response) {
            // return a Success Response in JSON format

        }).catch(function (err) {
           // return an Error Response in JSON format
        });
    });
  }
}

Can Somebody help me as to why am I getting this error?

Nested TransactionScope for NUnit TestFixure and SetUp

I derive from this base class in order to enclose each indivdual test into a transaction that is rolled back

 public abstract class TransactionBackedTest
        {
            private TransactionScope _transactionScope;

            [SetUp]
            public void TransactionSetUp()
            {
                var transactionOptions = new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TransactionManager.MaximumTimeout
                };

                _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions);
            }

            [TearDown]
            public void TransactionTearDown()
            {
                _transactionScope.Dispose();
            }
        }

Using this I also tried to setup a TestFixure transaction the same way:

[TestFixture]
    class Example: TransactionBackedTest
    {

        private TransactionScope _transactionScopeFixure;


        [TestFixtureSetUp]
        public void Init()
        {
            var transactionOptions = new TransactionOptions
            {
                IsolationLevel = IsolationLevel.ReadCommitted,
                Timeout = TransactionManager.MaximumTimeout
            };

            _transactionScopeFixure = new TransactionScope(TransactionScopeOption.Required, transactionOptions);


            SetupAllDataForAllTest();
        }

        [TestFixtureTearDown]
        public void FixtureTearDown()
        {
            _transactionScopeFixure.Dispose();
        }


        public void SetupAllDataForAllTest()
        {
            // Sql stuff here that will get undone from the TestFixtureTearDown scope dispose
        }


        [Test]
        public void DoSqlStuff1()
        {
            // Sql stuff here that will get undone from the TransactionBackedTest
        }

        [Test]
        public void DoSqlStuff2()
        {
            // Sql stuff here that will get undone from the TransactionBackedTest
        }
    }

The idea being that SetupAllDataForAllTest is ran once at the beginning and inserts all the base data that tests rely on. This base data needs to be deleted/rolledback once the tests are complete.

I also want each test isolated so they cannot interfere with each other as well.

The issue I am having right now is that after the first test, it states the TestFixture transaction has been closed, even though I only wanted it to close the SetUp transaction. My assumption is that if you Dispose() and inner transaction it diposes the outer, so I am not sure how to accomplish what I want to do

How do I test specific cases in unittest?

I have read the python documentation for unittest and found it a bit confusing. I have written a test file with methods for testing various classes and methods, along the lines of:

class test_class_Graph(unittest.TestCase):
    def __init__(self):
        test_graph = Graph()
    def test_method__init__(self):
        assertEquals(x, y)
    def test_method_node(self, name):
        node = test_graph.node(name)
        assertIsInstance(node, Node)
        assertEquals(node.name, name)
class test_class_Node(unittest.TestCase):
    etc

I have created some test-methods with 'if-else' statements, corresponding to 'if-else' statements in the actual methods. These are a kind of test-case - under certain conditions, the method should act one way, under other conditions, we expect the method to produce something different.

There are certain cases where I don't want to partition the set of possible conditions into 'if-else' statements, I just want to test a few 'samples' for more complicated methods. For example, if the input is a specific 'X', I want the output to be a specific 'Y'.

Where do I write specific test cases like this? Am I supposed to run my tests from the command line, entering inputs there? Or am I supposed to simply execute a test file from the command line with 'run', and somehow have a sequence of pre-selected inputs and expected outputs?

Setting array.length for unit test

If I am running a unit test that is testing the logic based only on the length of a passed in array, should I be concerned about setting the length of it explicitly?

For example:

function foo(arrayFoo) {
  return arrayFoo.length > 10 ? 'too long' : 'just right';
}

And for the test:

let testArray = [];
testArray.length = 11;

const expected = 'too long'
const actual = foo(testArray);

expect(actual).toBe(expected);

I understand that this is creating an array of undefineds but is there a better way or am I just being paranoid?

When using a RegEx in AutoFixture ISpecimenBuilder, Why do I always get back the same value?

My builder is set up to either deal with a Parameter or a Property. This may change in the future, but for now this is what I have in my builder:

public class UserNameBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
       var propertyInfo = request as PropertyInfo;
        if (propertyInfo != null && propertyInfo.Name == "UserName" && propertyInfo.PropertyType == typeof(string))
        {
            return GetUserName();
        }

        var parameterInfo = request as ParameterInfo;
        if (parameterInfo != null && parameterInfo.Name == "userName" && parameterInfo.ParameterType == typeof(string))
        {
            return GetUserName();
        }

        return new NoSpecimen(request);
    }

    static object GetUserName()
    {
        var fixture = new Fixture();
        return new SpecimenContext(fixture).Resolve(new RegularExpressionRequest(@"^[a-zA-Z0-9_.]{6,30}$"));
    }
}

My UserName object is a ValueType object and is as follows:

public class UserName : SemanticType<string>
{
    private static readonly Regex ValidPattern = new Regex(@"^[a-zA-Z0-9_.]{6,30}$");

    public UserName(string userName) : base(IsValid, userName)
    {
        Guard.NotNull(() => userName, userName);
        Guard.IsValid(() => userName, userName, IsValid, "Invalid username");
    }

    public static bool IsValid(string candidate)
    {
        return ValidPattern.IsMatch(candidate);
    }

    public static bool TryParse(string candidate, out UserName userName)
    {
        userName = null;

        try
        {
            userName = new UserName(candidate);
            return true;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    }
}

The UserName class inherits from SemanticType which is a project that provides a base for my value types.

Whenever I use AutoFixture as follows:

var fixture = new Fixture();
fixture.Customizations.Add(new UserNameBuilder());

var userName = fixture.Create<UserName>();

I always get the value "......" I thought I would get a different value each time. Is what I'm seeing expected behavior?

Thanks

Stubed object is calling real methods in codeception

I'm trying to run tests using codeception and his library for Mock and Stub. what's happening is that when i'm trying to run my test with my Stubs, it's raising an error that is implemented in my real classes.

I think that a Stub is way to isolate the test and emulate real objects. Why it's calling my real methods?

<?php

class FirstDegreeTest extends \Codeception\TestCase\Test
{
  /**
   * @var \UnitTester
   */
  protected $tester;

  protected function _before()
  {
    $this->max_threads = 30;
    $this->firstDegree = new AlThread\LoadControl\Measurer\FirstDegree($this->max_threads);

    $sensor = Stub::make("AlThread\LoadControl\Sensor\LoadAvg", array("getSystemLoad", Stub::consecutive(0, 1, -3, 1.1, null)));

    $this->firstDegree->setSensor($sensor);
  }

  public function testMeasure()
  {    
    $this->assertEquals(30, $this->firstDegree->measure());
  }
}
?>

So when I run the codeception (php codeception.phar run):

Time: 487 ms, Memory: 11.25Mb

There was 1 error:

---------
1) Test me (FirstDegreeTest::testMeasure)

  [PHPUnit_Framework_Exception] rewind() expects parameter 1 to be resource, null given
                                                                                                 #1  Codeception\Subscriber\ErrorHandler->errorHandler
#2  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:42
#3  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:55
#4  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:49
#5  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:61
#6  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:67
#7  /home/AlThread/src/LoadControl/Sensor/LoadSensor.php:10
#8  /home/AlThread/src/LoadControl/Measurer/LoadMeasurer.php:32
#9  /home/AlThread/tests/unit/FirstDegreeTest.php:31
#10 FirstDegreeTest->testMeasure

FAILURES!
Tests: 3, Assertions: 2, Errors: 1.

So here is the problem:

[PHPUnit_Framework_Exception] rewind() expects parameter 1 to be resource, null given

The traceback take me until the real implementation of class LoadAVG, where i'm realy calling the rewind() function, and obviously, raise an error, once this class doesn't have the appropriate environment to run.

Will be that I'm thinking about Stubs in the wrong way?

Thank you very much.

How to use the googlemock's Field matcher?

Suppose the following :

enum ElevatorDirection{UP, DOWN, NONE}

class ElevatorStatus
{
public:
    ElevatorDirection currentDirection;
}

Somewhere in my tests, I have :

using testing::Field;
using testing::Eq;

TEST(myTestCase, myTestName)
{
    EXPECT_CALL(*server, Broadcast(Field(&ElevatorStatus::currentDirection, Eq(ElevatorDirection::UP))));
    // ...
}

When I compile, I get a bunch of errors. The first one is :

../../../GoogleTest/gmock-1.7.0/include/gmock/gmock-matchers.h:437:47: required from ‘bool testing::PolymorphicMatcher::MonomorphicImpl::MatchAndExplain(T, testing::MatchResultListener*) const [with T = const std::basic_string&; Impl = testing::internal::FieldMatcher]’

tests/WebsocketInterfaceTest.cpp:48:1: required from here

../../../GoogleTest/gmock-1.7.0/include/gmock/gmock-matchers.h:2030:24: error: no matching function for call to ‘testing::internal::FieldMatcher::MatchAndExplainImpl(testing::internal::bool_constant::type, const std::basic_string&, testing::MatchResultListener*&) const’

If I comment the EXPECT_CALL(...) line, everything compiles fine. What am I doing wrong using the Fieldmatcher?

Jvm options in android when run gradlew test

I have a project that using Robolectric for unit test purpose. This project uses Robolectric 3.0 and need to add -ea and -noverify options in Virtual Machine options.

In Android Studio, I created new JUnit configuration in Run > Edit Configurations... and then set VM Options to -ea -noverify. With this way I success to run my unit test. This is image about my configure, view Here

However, for continuous deployment, I need run unit test with command line. So I use ./gradlew test to run unit test. I also add org.gradle.jvmargs=-ea -noverify to gradle.properties file. Unfortunately, it doesn't work. I can run unit test but I got java.lang.VerifyError and I think that gradle.properties was not load.

So, my question is, how to make gradle.properties load or do you know any way to fix my vm options problem?

Any way to print test case literally with Scala backticks

As we know, we can use backticks to declare a method name contains special characters, such as space, which sounds like a good way to say a unit test name. For example, we could declare a test case like this

class SampleTest {    
    @Test
    def `it should return a space` {
      ....  
    }
}

When I run this test case, I supposed to get the result

[info] Test run started
[info] Test SampleTest.it$u0020should$u0020return$u0020a$u0020space started
[info] Test run finished: 0 failed, 0 ignored, 1 total, 0.538s
[info] ScalaTest

All spaces display as $u0020. Is there any way to show spaces literally with JUnit test style?

[info] Test SampleTest.it should return a space started

I can't use Scala Spec test because I have to use JMockit in our test code.

JUnit reflects the method name it should return a space as it$u0020should$u0020return$u0020a$u0020space

Django tests: "DeserializationError: Prblem installing fixture '': need more than 1 value to unpack"

I'm developing a Django app and can't seem to get the first of my tests to run, due to an error associated with the fixtures. When I do "python manage.py test", I get this error:

stacktrace

Creating test database for alias 'default'...
E
======================================================================
ERROR: setUpClass (polladmin.tests.ModelsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/test/testcases.py", line 956, in setUpClass
    'database': db_name,
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
    return command.execute(*args, **defaults)
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
    self.loaddata(fixture_labels)
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata
    self.load_label(fixture_label)
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 141, in load_label
    for obj in objects:
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/serializers/json.py", line 85, in Deserializer
    six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/serializers/json.py", line 79, in Deserializer
    for obj in PythonDeserializer(objects, **options):
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/serializers/python.py", line 96, in Deserializer
    Model = _get_model(d["model"])
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/core/serializers/python.py", line 166, in _get_model
    return apps.get_model(model_identifier)
  File "/Users/username/Documents/ratchit/venv/lib/python2.7/site-packages/django/apps/registry.py", line 201, in get_model
    app_label, model_name = app_label.split('.')
DeserializationError: Problem installing fixture '/Users/username/Documents/ratchit/polladmin/fixtures/models.json': need more than 1 value to unpack

----------------------------------------------------------------------
Ran 0 tests in 0.006s

FAILED (errors=1)
Destroying test database for alias 'default'...

polladmin/tests.py

from django.test import TestCase

from models import *

class ModelsTestCase(TestCase):
    fixtures = ['models.json']

    def test_unique_title_for_polls(self):
        """ Test that new event cannot use the same title as existing """

        self.assertFalse(
            Poll.unique_title("Drinks"),
            "Duplicate event title not detected by Event.unique_title()")

polladmin/fixtures/models.json

[
  {
    "model": "event",
    "fields": {
      "pk": 1,
      "title": "Monty Python at the Hollywood Bowl"
    }
  },
 {
   "model": "poll",
   "fields": {
     "event": 1,
     "title": "Drinks"
   }
 },
 {
   "model": "poll",
   "fields": {
     "event": 1,
     "title": "Food"
   }
 }
]

How to test asyc retrofit calls in Android unit tests?

I am struggling to write unit tests for my API implementation in Android. I would like to test the Retrofit functionality but run into concurrency problems, where I do not know how to ensure that the async API calls get executed and finish before I start testing the Android internal database calls.

Here is my test function:

public class postPrintModeTest extends ActivityInstrumentationTestCase2<MainActivity> implements IConstants {
public MainActivity activity;

public postPrintModeTest() {
    super(MainActivity.class);
}

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

    String printModeName = "LSD Mode";
    int parentId = 4;
    Map<String, Object> payload = new HashMap<String, Object>();
    payload.put("name", printModeName);
    payload.put("parentId", parentId);

    APIExec.getInstance().postPrintMode(IConstants.authorization, IConstants.userId, IConstants.deviceUid, payload); // <- this needs to finish before I execute the tests, so I have proper data in the database.
}

@SmallTest
public void testPrintModeCreated() {
    DBPrintMode printMode = APIDBOps.getInstance().readPrintModeByPrintModeID(6);

    assertNotNull("Print Mode does not exist", printMode);
}

@SmallTest
public void testPrintModeName() {
    DBPrintMode printMode = APIDBOps.getInstance().readPrintModeByPrintModeID(6);

    if(printMode != null)
    {
        assertTrue("Print Mode name is not correct", printMode.getName().equals("LSD Mode"));
    }
}

}

and here is the async method in question:

public void postPrintMode(String authorization, final int userid, String deviceuid, final Map payload){
    api.postPrintMode(authorization, userid, deviceuid, payload, new Callback<PrintMode>() {

        @Override
        public void success(PrintMode printMode, Response response) {

            if (printMode.get_id() != 0) {
                dbOps.writePrintMode(userid, printMode);
                bus.getBus().post(new EVTNewPrintMode(printMode));
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace();
            APIUtils.showAPIResponseBody(retrofitError);
        }
    });
}

How can I mock/patch an associative array in python

I have a module with a dictionary as associative array to implement a kind-of switch statement.

def my_method1():
    return "method 1"


def my_method2():
    return "method 2"


map_func = {
    '0': my_method1,
    '1': my_method2
}

def disptach(arg):
  return map_func[arg]()

How can I mock my_method1 in tests? I've tried the following without success:

import my_module as app

@patch('my_module.my_method1')
def test_mocking_sample(self, my_mock):
    my_mock.return_value = 'mocked'
    assert_equal('mocked',app.dispatch('0'))

Any idea?

Make a class to be a Mockito mock without calling mock

I have a Java application based on Spring that uses services. For some reasons, I need to autowire a service that is implemented for for the sake of unit testing. I would like this autowired class to be a Mockito mock, such that I can pass it to all the Mockito methods (when(), etc.). Should I extend or implement some Mockito class?

E.g.

@Profile("test")
@Primary
@Service
public class MockAService implements AService {
    public void callMethod(){}
}

Then in the test I have

{
    System.setProperty("spring.profiles.active", "test");
}

@Autowired AService aservice;

and in the test method I want to do:

@Test
public void test(){
  doNothing().when(aService).callMethod();
}

Is it possible to only run one test class (that leverages PowerMock and Mockito)?

I am currently working on a project (with IntelliJ) with unit tests powered by PowerMock (for mocking final classes), and includes mocks using Mockito. The test suite takes a bit of time to run (via mvn test).

Is it possible to only run one test class (the one I'm working on)? It is a maven project, but I'm happy with any runner.

(If it helps with analogies/examples, I'm coming from a C#/NUnit background).

Why do both unit and functional tests

I am doing extensive functional testing for my restful application, and because the app follows rest principles the overhead is minimal. I cannot think of a concrete reason why I should also invest time and effort into writing/testing unit tests. Am I missing an obvious point?

Maven Integration Tests With Spring Dependency

I have a project structure where I have the two following (Mavenized) projects:

Database - This project is a Spring project which manages interaction with the webapp's database. It contains code for interacting with the database, as well as many service classes. The Application Context here contains the database connection information, as well as beans for each service class.

WebApp - This project is a JSF project which just contains the UI stuff.

For unit testing the Database project, I have a testing Application Context which communicates with a very simple in-memory database-like structure, so the real database is not modified. The testing portion of this project also contains the structure for the in-memory database.

File Structure:

src/main/java/...
src/main/resources/spring/applicationContext.xml
src/test/java/...
src/test/resources/spring/applicationContext.xml

I want to create automated integration tests for the WebApp project which still uses the in-memory database stuff, as well as the testing Application Context, from the Database project. Unfortunately, Maven doesn't provide the WebApp project with the Database project's test code, so it isn't even accessible.

I tried working around that by using the maven-jar-plugin with the test-jar goal and added the test-jar as a dependency in Eclipse (since I read to do that for this problem), however Eclipse gives me the well known: "Dependency to project database with type test-jar is not fully supported. Classpath and/or deployment issues might arise. Try Maven->Disable Workspace Resolution" message, and doesn't update the dependency code when I make changes to the Database project, which means I have to perform a Maven build every time I make a change in the Database project for the test code in the WebApp project to work with the changes.

Database Project:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

WebApp Project:

<dependency>
    <groupId>...</groupId>
    <artifactId>database</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>

Furthermore, Maven Clean no longer works on the Database project, since it says it cannot delete the test jar. Additionally, the command line doesn't run the tests with Database test jar, so the Maven Install on the WebApp project fails.

What should I do to make this work? I've heard about putting the test code into its own project and using that other project as a test dependency, but that won't work for me because the WebApp project needs to use the Database project's testing Application Context, so the problem is more than just access to the Database project's test code.

Null pointer exception when testing a rest web service

I get a null pointer exception when trying to test a web service

My code:

@Path("/")
public class SubscriptionService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/status/{subsId}")
    public Response getSubscriptionStatus(@PathParam("subsId") int subsId) {
        return Response.status(200).entity("subscription status for id: " + subsId).build();
    }
}

Test class:

public class TestService {

    private SubscriptionService service;

    @Test
    public void testGetSubscriptionStatus() {
        final Response response = service.getSubscriptionStatus(5);

        Assert.assertEquals(200, response.getStatus());
        Assert.assertEquals("subscription status for id: 5", response.getEntity());
    }
}

The error appears here: final Response response = service.getSubscriptionStatus(5);

Does anyone have any idea why I get this error? Please help with a solution.

How to stub out a generic method definition in an interface using Microsoft Fakes in c#

I have a unit test which stubs out the following interface using Microsoft Fakes:

public interface ITable
    {
        Task<TableResult> Retrieve(string tableReference, string partitionKey, string rowKey);
    }

The stub looks like this:

ITable table = new MessagesAPI.Azure.Fakes.StubITable()
            {
                RetrieveStringStringString = delegate
                  {
                      TableResult tableResult = new TableResult();
                      return Task.FromResult(tableResult);
                  }
            };

This works fine. However I'd like to change the interface to be more generic like so:

public interface ITable
    {
        Task<TableResult> Retrieve<T>(string tableReference, string partitionKey, string rowKey) where T : ITableEntity;
    }

Question is how would I stub this new version of the interface out? I'm having trouble getting the syntax right.

Any ideas?

Rspec rails unit test - Ruby on rails

I have this code for unit test:

require 'rails_helper'
require 'fetch_controller'

   RSpec.describe FetchController, type: :controller do
   it "parse base 64 url" do
     result = FetchController.parse_urls('aHR0cDovL3d3dy5nb29nbGUuY29t')

    expect(result[0]).to eq('http://www.google.com')

   end
 end

and I want to test parse_urls method that in fetch_controller:

class FetchController < ApplicationController
...
  def parse_urls(base)
  Base64.decode64(base).split(',')
end

But when i'm trying to run it I get an error ": in `require': cannot load such file -- fetch_controller (LoadError)"

Thanks for any help, Yoel

How do I get Karma Coverage to detect correctly

I'm using Jenkins to run my Karma tests of Angular, but the coverage shows 20% even though its actually 100%. How does Karma Coverage test for coverage, and how can I write my tests so they should be correctly detected?

For example if my test looks like:

describe("ControllerName function xYz removes a query", function() {
    it("tests that the query was removed", function() {
        spyOn('ControllerName',xYz);
        ControllerName.xYz();
        expect(ControllerName.xYz).toHaveBeenCalled();
    });
});

Should the describe or it have only the controller name or function name for the coverage to be detected?

dimanche 30 août 2015

Test if function has been called inside $scope.$watch

I'm trying to figure out how to test with karma jasmine if function was executed inside $watch with the conditions I need.

Here what is in the controller. $watch contains couple of condition.

 $scope.$watch('player', function (newVal, oldVal) {
    if (oldVal && newVal != undefined && newVal != oldVal) {
        if (newVal.email == oldVal.email && newVal.emWallet == oldVal.emWallet)
            $scope.saveSettings();
    }
}, true)

This is the part of the test

it('when player property is changed saveSettings calls', function () {

    var sspy = spyOn(scope, "saveSettings");
    expect(scope.player.email).toEqual('');
    expect(scope.player.emWallet).toEqual('');

    expect(scope.player.balance).toEqual(10.0000);

    //change player balance
    scope.player.balance = 10.0304;
    scope.$apply();

    expect(scope.player.email).toEqual('');
    expect(scope.player.emWallet).toEqual('');

    expect(sspy).toHaveBeenCalled();

});

In the test above I'm changing the property that is outside condition so player.email and player.emWallet still the same and expect the call of saveSettings() function inside, but get "sspy has never been called" error.

I would appreciate a lot if someone point me right direction.

Unit Testing a function inside a angular directive using jasmine

I have directive in angular js. Which adds a 'src' attribute to the image element as shown below.

myApp.directive('imageonload', ['$q',function($q) {
var dPromise;
function loadImg(scope,target,url)
{

    var deferred = $q.defer();
    dPromise = deferred.promise;

    var img = new Image();
            // onload handler (on the image, not the element) 
            img.onload = function() {
                img.onload = null;
                //target.src = url;                                        
                deferred.resolve(url);
            };
            img.onerror = function() {
                img.onerror = null;
                //target.src = url;                                                          
                deferred.resolve(url);
            };
            // set the source for the image to initiate the load
            img.src = url; 
            return dPromise;   
}

return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        loadImg(scope,element,attrs.url).then(function(data){
                element[0].setAttribute("src",attrs.url);
            scope.updateLoadCount();
        });

    }
};

}]);

now I wanted to test whether the attribute src is added to the element ?using jasmine test case.

The spec I have written is like

it("should set the url after loading image",function(){ 

   elm = angular.element("<img id='tnl_pic_2' class='ng-scope' url='http://ift.tt/1LMLGF7' imageonload=''>");
    elm = compile(elm)(scope);
    scope.$digest();
    scope.img = new Image();

    expect(elm.attr('src')).not.toBe('');
  });

But my spec always fails and there is no coverage for directive, src attribute is never added to the element

As I am beginner in jasmine and angular , could you please help me out in how to test this functionality of directive. Thanks in adv !

RSpec less strict equality expectation for test

I have the following test:

it "can add an item" do
    item = Item.new("car", 10000.00)
    expect(@manager.add_item("car", 10000.00)).to eq(item)
end

Item's initialize looks like:

  def initialize(type, price)
    @type = type
    @price = price
    @is_sold = false
    @@items << self
  end

Manager's add item looks like:

  def add_item(type, price)
    Item.new(type, price)
  end

This test is currently failing because the two items have different object ids, although their attributes are identical. Item's initialize method takes a type, and a price. I only want to check for equality on those features... Is there a way to test strictly for attribute equality?

I have tried should be, should eq, to be, and eql? with no luck.

How to test express config?

I've been trying to figure out how to test the configuration for an express server (ex. middleware, etc.). I haven't been able to find any examples, and I'm unsure if the best way to test it is to simply match the expected list of middleware to the actual list of middleware, do something else entirely, or even if it's just config that shouldn't be tested at all.

I should also add that I'm not as interested in how exactly to do it, but rather more in the higher level concept. But I'm using mocha and supertest if it helps.

How to test long nested properties method invocation?

how should I test methods which calling nested property method? Something like:

PropertyA.PropertyB.PropertyC.DoSomething();

Should I create mock for each property and check if method DoSomething() was called? Looks like a lot of test code for simple method invocation. Is there a better way?

Calling other class methods in unit testing

I have a class which contains a list of objects in it, which then uses to return the user a calculated value using these objects' states. E.g:

class MyContaier {
    private List<MyObject> m_listOfObjects;

    public MyContainer() {
        ...
    }

    public void addObject(MyObject object) { 
        m_listOfObjects.add(object);
    }

    public int calculateTotal() {
        int total = 0;

        for (MyObject object : m_listOfObjects)
            total += object.getValue();

        return total;
    }
}

I am trying to unit test calculateTotal method using junit and mockito, but in order to do that I need to add a few mocked MyObject instances to m_listOfObjects. However, this would mean calling another method in the calculatedTotal test, addObject.

Is this a valid unit test, or is it against the best practices as my test of calculateTotal also depends on addObject method?

samedi 29 août 2015

Unit Test of file upload using MockMvcBuilders with standalone context and SpringBoot 1.2.5

I'm using Spring Boot 1.2.5-RELEASE. I have a controller that receive a MultipartFile and a String

@RestController
@RequestMapping("file-upload")
public class MyRESTController {

  @Autowired
  private AService aService;

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  @ResponseStatus(HttpStatus.CREATED)
  public void fileUpload(
      @RequestParam(value = "file", required = true) final MultipartFile file,
      @RequestParam(value = "something", required = true) final String something) {
   aService.doSomethingOnDBWith(file, value);
  }
}

Now, the service works well. I tested it with PostMan and eveything goes as expected. Unfortunately, I cannot write a standalone unit test for that code. The current unit test is:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
public class ControllerTest{

    MockMvc mockMvc;

    @Mock
    AService aService;

    @InjectMocks
    MyRESTController controller;

  @Before public void setUp(){
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
  }

  @Test
  public void testFileUpload() throws Exception{
        final File file = getFileFromResource(fileName);
        //File is correctly loaded
        final MockMultipartFile multipartFile = new MockMultipartFile("aMultiPartFile.txt", new FileInputStream(file));

        doNothing().when(aService).doSomethingOnDBWith(any(MultipartFile.class), any(String.class));

        mockMvc.perform(
                post("/file-upload")
                        .requestAttr("file", multipartFile.getBytes())
                        .requestAttr("something", ":(")
                        .contentType(MediaType.MULTIPART_FORM_DATA_VALUE))
                .andExpect(status().isCreated());
    }
}

Test fails with

java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?

Now, in the MultipartAutoConfiguration class from Spring Boot I see that a MultipartResolver is auto configured. But, I guess that with the standaloneSetup of MockMvcBuilders I cannot access this.

I tried several configurations of the unit test that I don't report for brevity. Especially, I also tried rest-assured as shown here, but honestly this doesn't work because it seems that I cannot mock the AService instance.

Any solution?

Squire JS Mocking Not working in unit test

I am trying to use squirejs in a sample test but its not working. I have a couple of modules

Person.js

define(['scripts/boat','scripts/chicken'], function (myBoat,chook) { 

  var name, age;

  var api = {};


  api.setName = function (names) {
    name = names;
  };

  api.getName = function () {
    return name;
  };

  api.getBoatSpeed = function() {
    myBoat.setDriver(3);
    return myBoat.maximumSpeed();
  };

  api.getMarshal = function() {
    return chook.getFeathers();
  };


  return api;

});

Chicken.js

define(
[], function () {



return {

    getFeathers : function () {
        console.log('getFeathers called from actual module');
        return 100;
    }

};

});

In my test i am running a beforeEach

beforeEach(function(done) {
    injector = new Squire();
    injector.mock("scripts/chicken", mockFeatherService)
    .require(['scripts/person'], function (component) {
      myChicken = component;
    });
    done();
  });

and my mockfeatherservice looks like

var mockFeatherService = {

      getFeathers : function () {
        console.log('getFeathers called from MOCK module');
        return 1;
      }
    };

test which fails as it always returns 100 rather than the mocked 1.

 it('Its a chicken test', function() {

   expect(pers.getMarshal()).to.equal(1);

my issue is that the actual method 'getFeathers' seems to be called from the actual module rather than the mock created in the test - what am i doing wrong?

Test output :

29 08 2015 23:54:58.197:INFO [watcher]: Changed file "/Users/russellholmes/Desktop/require/test/test.js".
LOG: 'getFeathers called from actual module'
LOG: 100
LOG: 'getFeathers called from actual module'
Chrome 44.0.2403 (Mac OS X 10.10.3) When a person Its a chicken test FAILED
    AssertionError: expected 100 to equal 1

How to unit test a form submission when multiple forms on a route?

I want to add unit tests to my flask app that tests form behavior on valid and invalid logins + signups. Currently, I have the signup form and a login form hosted on one page and route, and am using a hidden input field to identify which of the two forms is submitted / determine next actions.

My question is - how do I write a unit test that targets a specific form on a page? All the examples I've seen so far post data to a specific route, which is currently what I am doing. But that is failing because I need an added way to say "and we're submitting x form".

So is there a way to add "and we're submitting x form" in the post request?

login unit test:

from app import app
import unittest

class FlaskTestCase(unittest.TestCase):

  #ensure that login works with correct credentials
  def test_correct_login(self):
    tester = app.test_client(self)
    response = tester.post(
      '/login',
      data = dict(username="test@gmail.com", password="test"),
      follow_redirects=True
      )
    self.assertIn(b'you are logged in', response.data)

login route in views.py:

@app.route('/login', methods=['POST', 'GET'])
def login():
  login_form = LoginForm()
  signup_form = SignupForm()
  error_login = ''
  error_signup = ''

  #login form
  if 'login_form' in request.form and login_form.validate():
   # do login form stuff

  #signup form 
  if 'signup_form' in request.form and signup_form.validate():
   # do signup form stuff

  return render_template('login.html', login_form=login_form, signup_form=signup_form, error=error)

login.html:

<div class="login-form form-400">
      <h3>Log In To Your Account</h3>
      <input type="hidden" name="login_form">
      {% if error_login != '' %}
      <label class="error">
        {{ error_login }}
      </label>
      {% endif %}

      {% from "_formhelper.html" import render_field %}
      {{ login_form.hidden_tag() }}
      {{ render_field(login_form.email, placeholder="Your Email", class="form-item__full", type="email") }}
      {{ render_field(login_form.password, placeholder="Your Password", class="form-item__full") }}
      <input type="submit" value="Login" class="button button-blue">
    </form>
  </div>

  <p class="login-divider">or</p>

  <div class="signup-form form-400">
    <h3>Create a New Account</h3>
    <form action="" method="post">
      <input type="hidden" name="signup_form">
      {% if error_signup != '' %}
      <label class="error">
        {{ error_signup | safe}}
      </label>
      {% endif %}

      {% from "_formhelper.html" import render_field %}
      {{ signup_form.hidden_tag() }}
      {{ render_field(signup_form.username, placeholder="Pick a Username", class="form-item__full") }}
      {{ render_field(signup_form.email, placeholder="Your Email", class="form-item__full", type="email") }}
      {{ render_field(signup_form.password, placeholder="Create a Password", class="form-item__full") }}

      <input type="submit" value="Sign Up" class="button button-green">
    </form>
  </div>

How to test signal-slot connections with qtest

I am just starting out with QT and would like to have unit tests. I found a blueprint for a project structure that supports having tests outside my application.

For my first test I wanted to have a click on the "Quit" menu point, checking that the close action of QMainWindow is really called.

Coming from Java with all its mocking frameworks, here is what I would like to do:

  1. Simulate Click on Menu (or key press)
  2. Click on Quit Action (or key press)
  3. Verify that signal "triggered()" of QAction was emitted
  4. Verify that slot "close" of QMainWindow was called

I read the qtest tutorial, KDE documentation and other stuff on the net but I am not able to express that using qtest (yet).

I found Qt UI testing: How to simulate a click on a QMenuBar item using QTest? which describes a similar thing, but even there only 1, 2, 3 are covered (And I was not even able to get them to work).

So how can I write such a test case? Is that even possible?

Guice, DI, and Unit Tests in Play 2.4

So I've been trying to figure this out on my own via documentation but I'm not getting anywhere.

I've got some simple DI bindings setup in a service class that creates a repository object. Simple. However, when I run this in test mode, @Inject does nothing and the repository object is never instantiated.

@Inject
TagRepository tagRepository;

So on the line where it's use, in test mode, we of course get a NullPointerException

tagRepository.tagExistsByName(tag);

This bubbles up into my test like so:

[error] Test services.TagsServiceTest.testAddNewTag failed: java.lang.NullPointerException: null, took 0.097 sec
[error]     at services.TagService.tagExists(TagService.java:27)
[error]     at services.TagService.addNewTag(TagService.java:18)
[error]     at services.TagsServiceTest.testAddNewTag(TagsServiceTest.java:29)

My question is, how do I configure my application to use Guice injectors in test mode? I didn't have this problem with my controllers because requests were actually being made to them, setting up the full application.

One thing I should mention is that I'm using a provider to provide my app to the tests. Should I be using the Guice application builder? If so, where does that go? The play docs aren't very helpful in that regard. Here is the provider

@Override
protected FakeApplication provideFakeApplication() {
    return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), ImmutableMap.of("play.http.router", "router.Routes"), new ArrayList<String>(), null);
}

Unit Testing an Object and a Variable that conforms to a protocol in Swift

I have a VIPER architecture setup and am trying to unit test the instantiation of the wireframe.

For anyone who doesn't know what VIPER is, the key parts to understand are that there is are 4 classes that that have key responsibilities. The wireframe creates the other 3 (the view, presenter, and interactor). The wireframe then connects them appropriately like below:

                              Wireframe
                                  ^
                                  |
                                  v
                     View <-> Presenter <-> Interactor

So I am creating the unit tests in Swift, and am having difficulty making sure these connections are setup. Note, the code itself works, the asserts in the unit tests are the problem.

    func testInitWithNothingShouldInstantiateVIPERStackAndConnectLayers() {
            wireframe = LoginWireframe()       

            XCTAssertEqual(wireframe.modulePresenter, wireframe.moduleInteractor.presenter, "Interactor's presenter must be the module's presenter")

            XCTAssert(wireframe.modulePresenter === wireframe.moduleInteractor.presenter, "Interactor's presenter must be the module's presenter")
    }

Neither of these two asserts compiles correctly.

For the XCTAssertEqual this error occurs

Cannot find an overload for 'XCTAssertEqual' that accepts an argument list of type '(LoginPresenter, LoginInteractorOutput, String)'

For the XCTAssert (or XCTAssertTrue), this error occurs

Cannot invoke 'XCTAssert' with an argument list of type '(Bool, String)'

For completeness and because someone may find the code useful:

//LoginWireframe.swift
class LoginWireframe: NSObject, LoginWireframeInterface {
    lazy var moduleInteractor = LoginInteractor()
    lazy var modulePresenter = LoginPresenter()
    lazy var moduleView = LoginView()
    lazy var presenter : LoginRouting = self.modulePresenter

    override init() {
            super.init()

            let i = moduleInteractor
            let p = modulePresenter
            let v = moduleView

            i.presenter = p

            p.interactor = i
            p.view = v
            p.wireframe = self

            v.presenter = p

            presenter = p
}

//LoginInteractor.swift
class LoginInteractor: NSObject, LoginInteractorInput {
    lazy var presenter : LoginInteractorOutput = LoginPresenter()
}

//LoginPresenter.swift
class LoginPresenter : NSObject, LoginInteractorOutput, LoginPresenterInterface, LoginRouting {
    lazy var interactor : LoginInteractorInput = LoginInteractor()
    lazy var view : LoginViewInterface = LoginView()
    lazy var wireframe : LoginWireframeInterface = LoginWireframe()
}

//LoginView.swift
class LoginView : UIViewController, LoginViewInterface {
    lazy var presenter : LoginPresenterInterface = LoginPresenter()
 }

AngularJS Jasmine unit test with httpBackend - rootScope variable is undefined

I have the following controller

app.controller('NavController', ['$rootScope', '$scope', 'api', function($rootScope, $scope, $location, auth, api) {
    $scope.load = function() {
        return api.get('/location').success(function(data) {
            $rootScope.locations = data;
        }).error(function(data) {
            console.log('load error');
        });
    };
}]);

And this is the unit test I have written for it

describe('Navigation Controller Test', function() {

    beforeEach(module('app'));

    var controller, scope, rootScope, httpBackend;

    beforeEach(inject(function(_$controller_, _$rootScope_, $httpBackend) {
        var $controller = _$controller_;
        rootScope = _$rootScope_;
        scope = rootScope.$new();
        httpBackend = $httpBackend;
        controller = $controller('NavController', {
            $rootScope: rootScope,
            $scope: scope,
        });

        apiRequestHandler = httpBackend.when('GET', '/api/v2/location')
            .respond({userId: 'userX'});

    }));

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    describe('load()', function() {
        it('should have locations when successful', function() {
            httpBackend.expectGET('/api/v2/location');
            scope.load();
            expect(rootScope.locations).toEqual("{userId: 'userX'}");
            httpBackend.flush();
        });
    });
});

The current issue I'm having is that rootScope.locations is undefined even after calling the scope.load() function. I'm not too sure why this is but the closest post I seem to have found is this one which I think might be related to my problem but I'm not quite certain.

I did a console.log($rootScope.locations) in the controller when the get request is successful and it had the correct output however I'm stumped on how to get it to appear the same for this test.

Unit testing for IBAction connection with good form

I've created a successful unit test that checks for an IBAction in Swift. However, the form isn't great:

func testAddButtonIBActionShouldExist() {
    let actions=viewController.addButton.actionsForTarget(viewController, forControlEvent: UIControlEvents.TouchUpInside)
    XCTAssertNotNil(actions, "Add button should have conections")

    if actions != nil{
        let actionsAsNSArray:NSArray=actions! as NSArray
        XCTAssertTrue(actionsAsNSArray.containsObject("addNumbers:"), "Add button not connected to correct IBAction")
    }
}

It separates the test for nil and the containsObject into two separate parts, and also includes an if… both of which I believe are bad unit testing form. Is there a way to somehow combine these in Swift 1.2 (or Swift 2)? Thanks for reading.

vendredi 28 août 2015

How can I replace Activity scoped dependencies with mocks using Dagger2

I have a scoped dependency in my Activity and I want to test that activity with some mocks. I have read about different approach that suggest to replace Application component with a test component during the test, but what I want is to replace the Activity component.

For example, I want to test the Activity against mock presenter in my MVP setup.

I believe that replacing component by calling setComponent() on Activity will not work, because Activity dependencies already injected via filed injection. so during the test, real object will be used.

How can I resolve this issue? What about Dagger1? Is it has the same issue?

Writing a basic test module in nodeunit

I am trying to use nodeunit and this is what I have. Following is testRunner.js:

#!/usr/bin/env node
var nodeunit = require('nodeunit');
var myTest = require('mytest.js');
nodeunit.runModule(myTest);

Following is myTest.js:

var testCase = require('nodeunit').testCase;
module.exports = testCase({
  setUp: function(callback) {
    // Called before all tests execute
  },
  tearDown: function(callback) {
    // Called after all tests execute
  },
  testFunction1: function(test) {
    // A test
  }
  testFunction2: function(test) {
    // Another test
  }
});

I try ./testRunner.js but I get:

TypeError: Cannot read property 'moduleStart' of undefined!

Unfortunately, nodeunit doc is not 100% clear about how to write test suites. I They have a few examples but they could make it better. What am I doing wrong?

Code coverage finally block

I have the following code construction:

try {
   //some code
}
catch(CustomException custExc) {
  //log
}
catch(CustomException2 custExc2) {
  //log
}
catch(Exception exc) {
  //log
}
finally {
  //some code
} 

I wrote unit tests: the first one covered the situation when an exception is not thrown (executing only try block code and finally block code) and 3 other which of them is covered each catch block once (executing try block one of catch block and finally block). Problem is that the Eclipse Emma plugin showed that I didn't covered finally block. Any ideas why can it happen?

MSTest 2015/2013 Hanging

I am trying to get some unit tests to run on a build server and when MSTest is called from the command line it goes over the [Ignored] tests, and on the first test it sits and hangs with no output.

I attached a debugger and decompiled MSTest and it seems to get stuck in Microsoft.VisualStudio.TestTools.CommandLine RunCommand : Command

public override CommandResult Execute(TmiAdapter tmiAdapter)
{
  new ResultsEventListener(this, CommandFactory.Tmi).Initialize();
  Executor.Output.WriteInformation((string) Messages.CommandLine_StartExecution, MessageType.Status);
  CommandResult commandResult;
  try
  {
    commandResult = tmiAdapter.Run(this);
    switch (commandResult)
    {
      case CommandResult.TmiNoTestToRun:
        Executor.Output.WriteInformation((string) Messages.CommandLine_NoTestsToExecute, MessageType.Warning);
        break;
      case CommandResult.Success:
      case CommandResult.BrokenLinksFound:
        this.m_autoEvent.WaitOne();
        if (!TmiAdapter.RunPassed(this))
          commandResult = CommandResult.TmiRunFailed;
        string resultsFileForRun = TmiAdapter.GetResultsFileForRun(this.RunId);
        if (!string.IsNullOrEmpty(resultsFileForRun))
          Executor.ResultManagerInstance.AddResultsGeneralInfoPair((string) Messages.CommandLine_ResultsFileLogged, resultsFileForRun);
        Executor.ResultManagerInstance.AddResultsGeneralInfoPair((string) Messages.CommandLine_RunConfigurationUsed, tmiAdapter.RunConfig.Name);
        Executor.ResultManagerInstance.ShowResultsSummary(TmiAdapter.GetTestRunOutcome(this.RunId));
        Executor.ResultManagerInstance.ShowAllRunErrors();
        break;
    }
  }
  catch (CommandLineException ex)
  {
    this.Error = ex.Error;
    commandResult = ex.Result;
  }
  return commandResult;
}

On this line this.m_autoEvent.WaitOne();

Is it possible to Unit Test a Coded WebTest request and assert based on the response?

I have written a framework for performance testing in C# for Visual Studio Web Performance Testing.

I have written a Unit Test class to test the base classes but I would also like to add a unit test each request so I can ensure the WebTests are working as expected by adding a WebTestPlugin to obtain the Response Status Code.

So far I have been unsuccessful and before I pull my hair out I thought I would ask if it is possible, unfortunately Google has not answered my question.

I can provide code if required but just imagine trying to write a unit test for a webtest yield return result.

Thanks in advanced for any help given.

How to test method condition using mockito

Mockito is used to mock object behavior but how do I check if the condition match if the method call is not an object call.

For example

boolean sameType= bloodType != null && bloodType.type.equals(patient.type);
if (sameType && transfusion(availability)) {
return true;
}

if (sameType && availability <= 0) {
reject.rejectBlood(info);
return false;
}

how do I cover those using mockito?

Make unit test pass only when callback is called

I'm trying to unit test a bit of code to make sure that a callback is invoked, but it seems that even without an "Assert"-call in the method it will pass. Consider the code example below:

public void Show_ShowSomeAdFormat_CallbackShouldBeInvoked()
{
    AdManager adManager = new AdManager();

    adManager.Show<VideoTestAdFormat>((response) =>
    {
        //Assert.Pass(); <--- With or without this, the test will pass. 
        //I need it to only pass if it reaches this. How is it done?
    });
}

If you read the comments I think you will understand what I am after.

Thank you!

How to Unit Test static resources served by Spring ResourceHandlerRegistry

I'm trying to unit test a new Spring MVC project. I have a passing test for the home controller serving index.jsp. I'm trying to test serving static resources served by the ResourceHandlerRegistry in my WebConfig.

Any tips on how to do this correctly? Below is my code:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class})
public class HomeControllerTest {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                            .build();
}

@Test
public void testGetHomepage() throws Exception { //passing :)
    this.mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andExpect(forwardedUrl("/WEB-INF/pages/index.jsp"));
}

@Test
public void testGetResources() throws Exception {   // TEST FAILS :( with 404
    this.mockMvc.perform(get("resources/css/test.css"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(forwardedUrl("/resources/css/test.css"));
}

}

Output from print():

    2015-08-28 12:53:09 WARN  PageNotFound:1136 - No mapping found for HTTP request with URI [resources/css/test.css] in DispatcherServlet with name ''

MockHttpServletRequest:
     HTTP Method = GET
     Request URI = resources/css/test.css
      Parameters = {}
         Headers = {}

         Handler:
            Type = null

           Async:
   Async started = false
    Async result = null

  Resolved Exception:
            Type = null

    ModelAndView:
       View name = null
            View = null
           Model = null

        FlashMap:

MockHttpServletResponse:
          Status = 404
   Error message = null
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

sails test controller not executing completely

I am using sailsjs v0.11

As mentioned in testing documentation, I have configured my app.

My UserController.test.js

var request = require('supertest');
console.log('log 1');
describe('UserController', function() {
  console.log('log 2');
  describe('index', function() {
    console.log('log 3');
    it('should return success', function(done) {
      console.log('log 4');
      request(sails.hooks.http.app)
        .get('/user')
        .expect(200, done);
    });
  });

});

If i execute PORT=9999 mocha test/bootstrap.test.js test/unit/**/*.test.js I can see only

log1
log2
log3

in my console. The code after console.log(log3) is not being executed. However My User.test.js in models is working fine.

What is the reason for that?

Laravel's TestCase method seeJson() only looks for array

I'm using Laravel 5.1 Testsuite.

Now, I test my json api with the method seeJson(). This method expects an array, such as:

->seeJson(['created' => 1]);

But my json api always returns a json object or an array with json objects with, in this case:

Response::json(['created' => 1], 200);

In the case above, my json api returns:

{created: 1}

But seeJson() looks for the given array exactly:

[created: 1]

I never get my tests pass without a match. How can I match?

How do I unit test a function

I have returned to dev after many years. Given the many years, and the changes in c++ dev since I last worked in the field, I consider myself fairly new to dev. I was given the task of learning how to unit test our gui functions using QTest. I read, copied and ran the QString example in qtest tutorial. I have read through the documentation as well. I have not found how to put it all together to actually test a function or class written outside of a qtest file. For example, I created a simple test gui that writes a string after a pushbutton click. However, I am not able to get my unit test to use the gui I created. Can you direct me to a more in-depth tutorial or document that gives a complete overview on how write and implement a unit test?

Fluent Assertions: applying equivalency options to collection members

So I want to use custom equivalency criterion in Fluid Assertions (.NET) for collection elements. When applied to class property this works perfectly:

var actual = new Dto() {Value = 1.11};
var expected = new Dto() {Value = 1.1};
actual.ShouldBeEquivalentTo(expected, options =>
            options.Using<double>(x =>
                x.Subject.Should().BeApproximately(
                    x.Expectation, 0.2))
                .WhenTypeIs<double>());

However, when I try to apply the same assertion to colleciton members, I get a failure:

var actual = new [] {1.11};
var expected = new[] {1.1};
...

I get this error:

Expected item[0] to be 1.1, but found 1.11.

With configuration:

  • Use declared types and members
  • Compare enums by value
  • Match member by name (or throw)
  • Invoke Action when info.RuntimeType.IsSameOrInherits(System.Double)
  • Be strict about the order of items in byte arrays`

Same thing happens when using ShouldAllBeEquivalentTo. Is this by design? Is this a bug? Am I missing a trick here?

Create a Mock for Stripe or use a Stub on Stripe object?

I'm writing tests for my Backbone app which uses Stripe. I am using mocha-phantomjs to run the tests. In my index.html file I ha <script src="http://ift.tt/KXmU7y" type="text/javascript"></script> to get the code for Stripe. However when I run the tests, I get the error: ReferenceError: Can't find variable: Stripe, which makes sense, because I'm not running the command for the tests with a ssl certificate.

I got it working by creating a local js file and copied stripe's minified code into it, thus overriding the need of a ssl certificate and my tests passed.

However my question is if this is best practice?

Should I rather create a sinon mock object of Stripe and use that instead or would it make more sense to stub the Stripe object as to prevent any calls being made to the Stripe API?

Mock a final method with PowerMock + EasyMock + JUnit 3

I've already searched in SO similar question..so that's why I'm asking from scratch....

I have a class, A, with some final instance methods. From another class, B, in B.instance.method I'm using the A instance final methods.

How can I mock the A instance final methods ? The problem is that after creating the mock with the PowerMock.createMock(A.class), when I should use the PowerMock.expect(...).andReturn(...) I can't use that method, since the only methods available are

  • PowerMock.expectLastCall()
  • PowerMock.expectNew(...)
  • PowerMock.expectPrivate(...)
  • PowerMock.expectStrinctNew(...)

Until now, I've followed the PowerMock tutorial, and I've made the following code run with some exception

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
class Test {

@Test
testMethod {
A Aobj = PowerMock.createMock(A.class);
PowerMock.expect... **====> that's the problem..I don't have the simple expect() but only those listed before**
PowerMock.expectLastCall().anyTimes();
PowerMock.replay(Aobj);
}

Thanks in advance.

Unit testing Swift 2.0, @testable import, and scheme targeting issues

I have recently converted my app, and unit tests over to Swift 2.0. I am using @testable import AppName in my Tests.swift files.

Due to an issue with not being able to execute subclasses in multiple targets (see here for the issue), my class EntityName can only be of Target Membership AppName, and NOT AppNameTests.

The problem is, once I switch over to the AppNameTests schema to run unit tests, code in the module AppName can't find the class EntityName and I get

Use of undeclared type 'EntityName'

How do I get AppName to compile when running tests from the AppNameTests scheme without that entity class not a member of the scheme?

python mock patch decorator behaves different for class methods and individual functions

Few times I've ran into a problem with unittest.mock.patch decorator. When I tried to mock individual functions from included module, patch didn't work. However if functions from included module are collected as class methods, patch works perfectly.

Partially this question intersects with mine. But there is no good answer for this issue as well.

Here is an example of what I'm trying to describe:

|-- __init__.py
|-- helpers.py
|-- main_module.py
|-- tests.py

I wrote one function in helpers.py as a class method, and another one as an individual function:

# helpers.py
class HelperClass():

    def function_a(self):
        return "a"

def function_a():
    return "a"

I've included both of them in the main module:

# main_module.py    
from helpers import HelperClass, function_a


    def function_which_uses_helper_function():
        a_val = function_a()
        return a_val

    def function_which_uses_helper_class():
        a_val = HelperClass().function_a()
        return a_val

And finally tests:

# tests.py
from unittest import TestCase
from unittest.mock import patch
from main_module import function_which_uses_helper_function, function_which_uses_helper_class


class TestClass(TestCase):

    @patch('helpers.function_a')
    def test_function_which_uses_helper_function(self, mock_function_a):
        mock_function_a.return_value = "c"
        self.assertEqual(function_which_uses_helper_function(), "c")

    @patch('helpers.HelperClass.function_a')
    def test_function_which_uses_helper_class(self, mock_function_a):
        mock_function_a.return_value = "c"
        self.assertEqual(function_which_uses_helper_class(), "c")

Which gives me these results:

$ py.test tests.py
<...>
tests.py .F
<...>
tests.py:11: in test_function_which_uses_helper_function
    self.assertEqual(function_which_uses_helper_function(), "c")
E   AssertionError: 'a' != 'c'
E   - a
E   + c
============ 1 failed, 1 passed in 0.14 seconds ============

I'll appreciate any help. Hope this also helps someone :)

How to set Expectation for Linq query

Using Rhino Mocks:

        var list = MockRepository.GenerateMock<List<Foo>>();
        list.Expect(e => e.Any(Arg<Func<Foo, bool>>.Is.Anything)).Return(false);

It throws

ArgumentNullException: Value cannot be null. Parameter name: predicate

How do I write this well?

How to extract parameters stored in mock.call

I am unit testing the following functions:

import uuid


def process_name(id, name, weight):
    print('process_item:', id, name, weight)


def process_list(names):
    for (name, weight) in names:
        id = uuid.uuid4()
    process_name(id, name, weight)

My unit test looks as follows:

import unittest
from mock import patch, call
import SomePackage.SomeModule


class MyTestCase(unittest.TestCase):
    def test_something(self):
        items = [('Joe', 190), ('Dan', 200)]
        with patch('SomePackage.SomeModule.process_name') as mock_process_name:
            SomePackage.SomeModule.process_list(items)

I cannot match the whole mock_calls thing, because the first parameter submitted to it is a guid, and as such it will be different every time I call the function:

print(mock_process_name.mock_calls)
[call(UUID('some randomish guid'), 'Joe', 190),
 call(UUID('some other guid'), 'Dan', 200)]

I want to extract the parameters, and only match the non-volatile ones:

 print(mock_process_name.mock_calls[0][1][1:])
 print(mock_process_name.mock_calls[1][1][1:])
 ('Joe', 190)
 ('Dan', 200)

I know that I can also mock the thing which returns guids, and provide a fixed list of values in its side_effect. However, I feel quite lazy needing to mock too many things like uuid.uuid4(), datetime.now() and such. This is why I am looking for an alternative to mocking each and every volatile function.

Is there a more readable alternative to mock_calls[0][1][1:]?

How to mock Java Path API with Mockito

Java Path API is a better replacement of Java File API but massive usage of static methods makes it difficult to mock with Mockito. From my own class, I inject a FileSystem instance which I replace with a mock during unit tests.

However, I need to mock a lot of methods (and also creates a lot of mocks) to achieve this. And this is repeatly so many times across my test classes. So I start thinking about setup a simple API to register Path-s and declare associated behaviour.

For example, I need to check error handling on stream opening. The main class:

class MyClass {
    private FileSystem fileSystem;

    public MyClass(FileSystem fileSystem) {
        this.fileSystem = fileSystem;
    }

    public void operation() {
        String filename = /* such way to retrieve filename, ie database access */
        try (InputStream in = Files.newInputStream(fileSystem.getPath(filename))) {
            /* file content handling */
        } catch (IOException e) {
            /* business error management */
        }
    }
}

The test class:

 class MyClassTest {

     @Test
     public void operation_encounterIOException() {
         //Arrange
         MyClass instance = new MyClass(fileSystem);

         FileSystem fileSystem = mock(FileSystem.class);
         FileSystemProvider fileSystemProvider = mock(FileSystemProvider.class);
         Path path = mock(Path.class);
         doReturn(path).when(fileSystem).getPath("/dir/file.txt");
         doReturn(fileSystemProvider).when(path).provider();
         doThrow(new IOException("fileOperation_checkError")).when(fileSystemProvider).newInputStream(path, (OpenOption)anyVararg());

         //Act
         instance.operation();

         //Assert
         /* ... */
     }

     @Test
     public void operation_normalBehaviour() {
         //Arrange
         MyClass instance = new MyClass(fileSystem);

         FileSystem fileSystem = mock(FileSystem.class);
         FileSystemProvider fileSystemProvider = mock(FileSystemProvider.class);
         Path path = mock(Path.class);
         doReturn(path).when(fileSystem).getPath("/dir/file.txt");
         doReturn(fileSystemProvider).when(path).provider();
         ByteArrayInputStream in = new ByteArrayInputStream(/* arranged content */);
         doReturn(in).when(fileSystemProvider).newInputStream(path, (OpenOption)anyVararg());

         //Act
         instance.operation();

         //Assert
         /* ... */
     }
 }

I have many classes/tests of this kind and mock setup can be more tricky as static methods may call 3-6 non-static methods over the Path API. I have refactored test to avoid most redondant code but my simple API tends to be very limited as my Path API usage grown. So again it's time to refactor.

However, the logic I'm thinking about seems ugly and requires much code for a basic usage. The way I would like to ease API mocking (whatever is Java Path API or not) is based on the following principles:

  1. Creates abstract classes that implements inteface or extends class to mock.
  2. Implements methods that I don't want to mock.
  3. When invoking a "partial mock" I want to execute (in preference order) : explicitly mocked methods, implemented methods, default answer.

In order to achieve the third step, I think about creating an Answer which lookup for implemented method and fallback to a default answer. Then an instance of this Answer is passed at mock creation.

Are there existing ways to achieve this directly from Mockito or other ways to handle the problem ?

Why are Interface Mocks More Desirable than Subclass Mocks when Unit Testing?

When a class implements an interface, then it is easy to mock, but, you have to create an interface for it.

You can also mock by subclassing and overriding. If your base class provides a parameterless protected constructor, then your subclass mocks are not tied to changes in the base class constructor.

At first glance, it seems like the subclassing method to creating mocks is more desirable than creating interfaces for everything, but obviously, that's not how most people are doing it.

So, why are mocks based on interfaces considered better practice than mocks based on subclassing?

How to configure default coverage runner in idea?

I know that in idea I can choose coverage runner on Run/Debug configuration like this:

enter image description here

but then I select class in tree I see the following menu:

enter image description here

And I cannot configure coverage runner here.

Is it possible to configure coverage runner tool to use by default?

Displaying the Description attribute of a Unit Test in Visual Studio 2015

Does anyone know how to display the description attribute during a test run in Visual Studio 2015?

For example given this test:

        [TestMethod]
        [TestCategory("With Fakes")]
        [Description("Posting a blog entry without the required data should return a BadRequest")]
        public async Task BlogEntryPostTest1()
        {
          ... do test
        }

How would I get the description to display when running? I don't think Test Explorer will do it; is there any alternative?

Call external function in unit test

I'm trying to learn qunit test; I'm an OpenUi5 developer and I use Webstorm IDE every day. Webstorm allows me to config a Karma run configuration. I have created a simple karma configuration file and I have wrotten a test file test1.js:

test("Test function sum()",
  function() {
    ok(sum(0, 0) == 0, "the sum of 0 with 0 is 0");
    ok(sum(2, 0) == 2, "the sum of 2 with 0 is 2");
    ok(sum(2, 1) == 3, "the sum of 2 with 1 is 3");
    ok(sum(2, -1) == 1, "the sum of 2 with -1 is 1");
    ok(sum(-2, 1) == -1, "the sum of -2 with 1 is -1");
  });


function sum(a, b) {
  return a + b;
};

Good! sum fnction in inside the same file. But now I want start to test function in my js folder of projesct; for example in js/util.js I have getShortIdGrid function:

//util.js file
ui5bp.control = {
  ...
  getShortIdGrid: function(sFromId) {
      if (sFromId.lastIndexOf("_") < 0)
        return sFromId;
      else
        return sFromId.substring(0, sFromId.lastIndexOf("_"));
  },
  ...
}

How can I call ui5bp.controlgetShortIdGrid in my test?

Karma console show me ReferenceError: ui5bp is not defined

Unit testing of a function that doesn't return any value

I am doing unit testing in c++ using cppunit. I have seen some examples over internet that are showing testing a function that return some value. I have some functions in my project that do not return any value but do some calculations inside. Here I want to test the calculations inside those functions whether calculations are being done correctly or not, how can I do it? For example I have a function

void Flash::SerializeToBytes(Buffer &buffer) const
{
    // calculations
} 

how to execute a single unit test case using activator?

we are using play framework and activator as a build tool,we have many unit test cases written in out project,can you please tell me how to run single unit test case using activator ? i tried running this command in command line

activator test-only SampleNodeServiceImplTest. but this command is running all the test cases in the project. but i want to run only one specific unit test case.

TFS Build 2013 TestAdapterPath

I have multiple builds defined for continuous integration but due to incompatibilities I had to write my own TestAdapter for one project. The problem is that the other TestAdapters (NUnit & MsTest) detect these tests and try to run them and fail, then my custom adapter finds them and they run successfully. So the test report at the end has each test listed multiple times with a status of "Not Runnable" along with a passed result from my adapter. The other projects need NUnit & MsTest so I can't just remove them.

From the commandline I can run vstest.console.exe /TestAdapterPath to a folder with only my TestAdapter and everything works but I cannot find this option in TFS Build.

I'm using the build process template TfvcTemplate.12.xaml

I tried adding a filter based on TestCategory, then having my TestAdapter automatically add this property to each discovered test assuming the other TestAdapters will then skip these tests but that doesn't change anything, the other TestAdapters still run the tests ignoring my filter. Although I'm unsure if the Category is even working because it is not listed in the resulting report.

Test Result Report Screenshot

HSQL database occasional executes schema.sql twice

I have some non-deterministic behavior with HSQL database in Spring. On occasion, sequence is generated twice and DataSource initialization fails due to that.

The odd thing is, if it fails, it is always from the test which tries to read database entry that doesn't exist. The other tests which read existing entries don't fail.

I really don't understand what did i do wrong and why this happens.

Here is my configuration:

@EnableJpaRepositories
@EnableTransactionManagement
@Configuration
@Profile("test")
public class TestDatabaseConfig {

@Bean
@Primary
public EntityManagerFactory entityManagerFactory() throws ClassNotFoundException {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false);
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan(ENTITIES_PACKAGE);
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();
    return factory.getObject();

}

@Bean
@Primary
public DataSource dataSource() {

    return new EmbeddedDatabaseBuilder().addDefaultScripts()
                                        .setType(EmbeddedDatabaseType.HSQL)
                                        .build();
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) throws ClassNotFoundException {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory);
    return txManager;
    }
}

And the schema.sql:

CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1;
CREATE TABLE voucher (id INTEGER, code VARCHAR(64) NOT NULL UNIQUE, type VARCHAR(64) NOT NULL, state VARCHAR(64) NOT NULL, class_name VARCHAR(64), serial VARCHAR(64), consumption_user VARCHAR(255), creation_date TIMESTAMP DEFAULT current_timestamp, consumption_date TIMESTAMP, expiry_date TIMESTAMP)

data.sql:

-- VALID
INSERT INTO voucher (id, code, type, state, serial ) VALUES (1,'success', '1', 'E', 'serial: 123');

--ALREADY CONSUMED
INSERT INTO voucher (id, code, type, state) VALUES (2,'used', '1', 'U');

-- DATE EXPIRED
INSERT INTO voucher (id, code, type, state, expiry_date) VALUES (3,'expired', '1', 'E', DATE '2014-12-12');

And the error trace, at the top you can see sequence being generated twice sometimes:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement at line 1 of resource class path resource [schema.sql]: CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1; nested exception is java.sql.SQLSyntaxErrorException: object name already exists: VOUCHER_ID_SEQ in statement [CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE] ... 158 common frames omitted Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement at line 1 of resource class path resource [schema.sql]: CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1; nested exception is java.sql.SQLSyntaxErrorException: object name already exists: VOUCHER_ID_SEQ in statement [CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1] at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:474) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:208) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:49) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.initDatabase(EmbeddedDatabaseFactory.java:159) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.getDatabase(EmbeddedDatabaseFactory.java:132) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder.build(EmbeddedDatabaseBuilder.java:251) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] at com.siemens.ott.TestDatabaseConfig.dataSource(TestDatabaseConfig.java:46) ~[test-classes/:na] at com.siemens.ott.TestDatabaseConfig$$EnhancerBySpringCGLIB$$6a150586.CGLIB$dataSource$1() ~[spring-core-4.1.6.RELEASE.jar:na] at com.siemens.ott.TestDatabaseConfig$$EnhancerBySpringCGLIB$$6a150586$$FastClassBySpringCGLIB$$125e7bce.invoke() ~[spring-core-4.1.6.RELEASE.jar:na] at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE] at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE] at com.siemens.ott.TestDatabaseConfig$$EnhancerBySpringCGLIB$$6a150586.dataSource() ~[spring-core-4.1.6.RELEASE.jar:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45] at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE] ... 159 common frames omitted Caused by: java.sql.SQLSyntaxErrorException: object name already exists: VOUCHER_ID_SEQ in statement [CREATE SEQUENCE voucher_id_seq AS INTEGER START WITH 100 INCREMENT BY 1] at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source) ~[hsqldb-2.3.2.jar:2.3.2] at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source) ~[hsqldb-2.3.2.jar:2.3.2] at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source) ~[hsqldb-2.3.2.jar:2.3.2] at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source) ~[hsqldb-2.3.2.jar:2.3.2] at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:459) ~[spring-jdbc-4.0.9.RELEASE.jar:4.0.9.RELEASE] ... 175 common frames omitted Caused by: org.hsqldb.HsqlException: object name already exists: VOUCHER_ID_SEQ

jeudi 27 août 2015

Why can't I use @InjectMocks field matching when running with PowerMockRunner?

I've run into an issue in which the field injection matching for Mockito's @Mock annotation for @InjectMocks is not working in the case where there are 2 @Mocks of the same type. I've used the @Mock (name = "name_of_var") syntax as well, but it still failed...

Here is the class under test:

    import java.util.Date;
    public class Parent{

    private Date dateA;
    private Date dateB;

    public void setDateA(Date _dateA){
       dateA = _dateA;
    }

    public void setDateB(Date _dateB){
       dateB = _dateB;
    }

    public Date getDateA(){
       return dateA;
    }

    public Date getDateB(){
       return dateB;
    }

Here is the test itself:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({System.class, Parent.class})
    public class testParent{

    @Mock (name = "dateB")  private Date someOtherDate;
    @Mock (name = "dateA")  private Date someDate;    

    @InjectMocks Parent p;

    @Before
    public void setup(){
        Mockito.when(someOtherDate.getTime()).thenReturn(500l);
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.currentTimeMillis()).thenReturn(2000l);
    }

    @Test
    public void testGetDateAGetTimeShouldReturn1000() {
        Mockito.when(someDate.getTime()).thenReturn(1000l);
        Date result = p.getDateA();
        assertEquals(1000l, result.getTime());
    }

    @Test
    public void testGetDateBGetTimeShouldReturn500() {
        Date result = p.getDateB();
        assertEquals(500l, result.getTime());   
    }

When tested, both assertEquals cause a NullPointerException due to the fact that the @InjectMocks did not work.

Now, when I replaced @RunWith(PowerMockRunner.class) with @RunWith(MockitoJUnitRunner.class), it WORKS just fine.

Also, if I had just defined 1 Date variable ( say, dateA ) in Parent.java and a matching mock to inject in ParentTest, it would inject just fine using PowerMockRunner.class.

The reason I must run with PowerMockRunner.class is because I must be able to mock static functions as well as constructors.

I am running with Junit4.12, Mockito-all-1.10.19, and PowerMock-mockito-1.6.2-full.

Does anyone see the cause of why it does not inject properly with PowerMockRunner.class? Is there a workaround for this while running with PowerMockRunner.class?

Career Advice Needed. Job offer from company using Coldfusion and no version ctrl

I have a junior developer job offer for a company that promises career training, challenging projects and development autonomy. They are a leader in their field and have over 200 employees. They are in a desirable downtown location and hire people around my age (just out of school).

The only thing is that they don't use version control and their stack is Coldfusion. The company doesn't have a test database either. Would you sign on to get the immediate programming autonomy or pass to look for something else?

How to organize test cases for a class with many methods?

The application that I'm working on does three things for every input (a unique id)

  1. Extract information from multiple source pertaining to that id
  2. Validate the information that I extract

    2.1 If the validation succeeds then go on to the next extraction

    2.2 If the validation fails, then do the first step for the next id

  3. After extraction is done from all the service, I get all the information, transform and form the value object

For Extraction, I have created a class for every service I'm hitting and getting the information.

I access the object of the extract classes in the transformation and perform the transformation.

My transformation class looks something like this:

        builder
        .field1(getField1(extract1))
        .field2(getFiedl2(extract1, extract2))
        .field3(getField3(extract3))
        ....
        .field100+(getField(extract..))
    return builder;

Now, I want to write test cases for the transformation I am doing. I am having trouble in organizing the test cases.

If I create a class for every method, then I would end up in more that 100 classes. Also If I take the approach of 1 test class per class then I would be writing all the test cases in one class and it would become really hard to understand.

Could anyone suggest what should be done?

AngularJS Unit Tests: Injected Services undefined

I have difficulties unit testing angularJS due to the injector not injecting properly. Anything I inject turns out to be undefined.

Module:

app.module.js

angular.module('myServices', []);

AngularTest.js

describe('AngularTest', function() {

    beforeEach(module('myServices'));

    var scope;

    beforeEach(inject(function(_$rootScope_) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        scope = _$rootScope_;

    }));

    describe('Testing Angular injection', function() {

      it('scope should be defined', function() {    
        expect(scope).toBeDefined(); // fails
      });

    });
});

I have successfully tested controllers in my main module, however, this particular module is testing my sanity.

Any ideas ?

How to reuse angular javascript unit test modules?

I'm new to angular js, trying to write unit test for a function with experiment flags (defined in the build file) on and off respectively, in two different files.

In the first file:

describe('MyController', function(){
    var x = var_x;
    beforeEach(...);
    describe('TestFun', function (){
        it('should be **true** when flag is on', function(){
            expect(TestFun(x).toBe(**true**);
        });
    });
});

In the second file:

describe('MyController', function(){
    var x = var_x;
    beforeEach(...);
    describe('TestFun', function (){
        it('should be **false** when flag is off', function(){
            expect(TestFun(x).toBe(**false**);
        });
    });
});

The test can pass, however, there is a lot of duplication in these two files. Is there a fancier way to write these two tests without these duplications? Thanks!

Issue with Android Junit concurrency

I have a Android JUnit test extending ServiceTestCase. I have a number of test that successfully run, however one of my tests is having a problem.

The test begins a series of events that require the Service that I'm testing to save an image file. My JUnit test is then supposed to check the pixel size of the file to make sure the service is outputting the correct size of image.

At first I thought it was just a timing issue, which is something I expected and I wrapped my reading function in a while loop. However, no matter how long end up waiting the file never seems to complete until after the test completes. I can just run the test twice (since then the files are there for interrogation), but that kind of eliminates the usefulness of the Unit Test!

I had even went so far as causing the series of events with the service to start on a different thread to ensure that I wasn't locking up the thread somehow, but no luck

Any help would be appreciated.

Here is the code that I'm currently reading the file in with

    private HeightWidth readOutPutImageSize()
  {

    Bitmap bitmap = null;
    int iterations = 10;
    while ((iterations > 0) && (bitmap == null))
    {
      String fileNameAndPath = "/mnt/extSdCard/asdf/Logs/test.png";
      bitmap = BitmapFactory.decodeFile(fileNameAndPath);
      sleep(500);
      iterations--;
    }

    HeightWidth hw = null;

    if(bitmap != null)
    {
      hw = new HeightWidth(bitmap.getHeight(), bitmap.getWidth());
    }
    return hw;
  }

Strange behavior with SpringBoot unit testing and Jackson json manipulation

I have a rest controller implemented in Java using Spring Boot. It returns an entity, and I tested this controller using PostMan. Result is a nice json of the entity (status code is 200). Now, when I run the unit test the status code is 500. I removed from the entity the annotation @JsonSerialize used in a Date field, i.e.:

@JsonSerialize(using = JsonDateSerializer.class)
private Date adate;

where the serializer is:

@Component
public class JsonDateSerializer extends JsonSerializer<Date> {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void serialize(final Date date, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
        gen.writeString(DATE_FORMAT.format(date));
    }
}

And now I get a status code 200 in the test.

The test method relies on the starter-test module of Spring boot and is:

@Test
public void test(){
    mockMvc.perform(get("/rest/path"))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$", hasSize(1)))
                    .andExpect(jsonPath("$[0].id", is(1)))
                  .andExpect(jsonPath("$[0].adate", is("2015/01/01")));
}

When the annotation is on, the exception is:

015-08-27 22:43:17.502  WARN 8680 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: (was java.lang.UnsupportedOperationException) (through reference chain: com.google.common.collect.SingletonImmutableList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.UnsupportedOperationException) (through reference chain: com.google.common.collect.SingletonImmutableList[0])
2015-08-27 22:43:17.504  WARN 8680 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Handler execution resulted in exception: Could not write content: (was java.lang.UnsupportedOperationException) (through reference chain: com.google.common.collect.SingletonImmutableList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.UnsupportedOperationException) (through reference chain: com.google.common.collect.SingletonImmutableList[0])

java.lang.AssertionError: Status 
Expected :200
Actual   :500
 <Click to see difference>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:655)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:166)
    at com.rest.RestControllerTest.test(RestControllerTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:85)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:241)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
    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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Pom looks like:

    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.3.0.M3</version>
      <relativePath/>
    </parent>

with dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Why that annotation doesn't work? How can I fix the unit test?