mercredi 31 août 2016

JdbcTemplate not configured when using @DataJpaTest

I created a test with @DataJpaTest annotation. hsqldb is configured but I'm getting error:

No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate]

In the project I'm using JPA repositories and JdbcTemplates. It is working fine when I'm using real Oracle DB configuration. Why JdbcTemplate is not configured automatically ? What should I do in order to fix this problem ?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class})
@DataJpaTest
public class IntegrationTest

Dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>args4j</groupId>
    <artifactId>args4j</artifactId>
    <version>2.33</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-remote-shell</artifactId>
</dependency>

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

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

<dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3.0</version>
</dependency>

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-core</artifactId>
    <version>1.4.18</version>
</dependency>
<dependency>
    <groupId>org.perf4j</groupId>
    <artifactId>perf4j</artifactId>
    <version>0.9.16</version>
</dependency>
<dependency>
    <groupId>io.reactivex</groupId>
    <artifactId>rxjava</artifactId>
    <version>1.0.13</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>

How to make an maven API test module with implicit dependency on implementation to test within IDE?

context of the question: I'm currently developing some java system library wich presents layer between data source and user buisnesslogic. To test its functionality, data provider(in my case it is data grid) must be launched every time a new test is processed.

so, to improve test execution performance, a test infrastructure was made in an independent maven module. It launches data source once and then just clears its contents for every new test.

the problem itself: Now there is a necessity to give buisnesslogic developers our test infrastructure because of the same performance reasons. But it can't be done that simple because test infrastructure contains some system components of our library.

So,

Suppose we have a module A with your library implementation, and a module B with some test infrastructure, that contains dependencies on that implementation.

the question: Is there a way we can make a module C with accesses only API from module A at compile time (tests and sources) and can use test infrastructure from module B?

The build manager is

Maven 3.3.3

Test are made using

JUnit 4.11

Java IDE is

IntelliJ IDEA

what i've tried:

I've tried to resolve this issue using different Maven scopes like this:

Module A pom dependencies:

<dependencies>
  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleAAPI</artifactId>
  </dependency>
</dependencies>

Module B pom dependencies:

<dependencies>
  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleA</artifactId>
    <scope>provided</scope>
  </dependency>
</dependencies>

Module C pom dependencies:

<dependencies>
  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleB</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleAAPI</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

But, using provided means that we need to specify ModuleA on classpath when running tests from moduleC. Thats is OK, when using surefire plugin, but how to achieve the same when running tests from IDE?

Another possible option is to add runtime dependency on moduleA like this:

<dependencies>
  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleB</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleAAPI</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>my.group</groupId>
    <artifactId>moduleA</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>

But, using runtime scopes indicates that sources from moduleA will be accesible at test compile time (Introduction to the Dependency Mechanism). And I need only API to be accessible. There is already a question abuot some alternative scope:

Declare Maven dependency as test runtime only

Is there any alternative to these two options?

angular test case $scope.$apply

Why is it mandatory to execute $scope.$apply() in a test case for async process to finish.

say i have a service

angular.service("a",function($q){
    return {
        getValue: function(){
            return $q.resolve(someObj)
        }
    }
})

And in my test

it("test this",function(done){
    a.getValue()
    .then(function(data){
        expect(data).toEqual(data)
        done();
    })
    $scope.$apply();
})

Testing a service in angular2

My app appModule has

@NgModule({
    imports: [
       ...
  ],
  providers: [
    SdkService,
    MyOtherService
  ],
  bootstrap: [
     ...
  ]
})

MyOtherService which used the SdkService looks look this

import {SdkService} from '../sdkService';
@Injectable()
export class MyOtherService {
 constructor(
    private _sdk: SdkService
    ) {}

 public myMethod(): Observable<any[]> {
    ....}
}

Now I'm trying to test MyOtherService.MyMethod and cannot figure it out. I need that sdk to be a Mock service.

import { SdkService } from '../sdkService';
import { MyOtherService } from './MyOtherService'; 

describe('Testing Service', () => {
    beforeEach(async((MyOtherService: MyOtherService) => {
        TestBed.configureTestingModule({
            providers: [{
                provide: SdkService,
                useClass: MockSdkService
            }, MockSdkService],
            imports: [
                MyOtherService
            ]
        });
    }));

    it('should work', () => {
        let fixture: ComponentFixture<MyOtherService> = TestBed.createComponent(MyOtherService);
        fixture.detectChanges();

        fixture.componentInstance.myMethod().toPromise().then( (result) => {
            expect(result.prop.length).toBe(1);
        });
    });

});

Should I even be using createcomponent to test a service?

Mockito: Testing behavior when mock objects cant be injected

I have a method defined as

@Startup
@Singleton
public class PRCConnectionRunner { 

@Inject 
private ServiceStatus status;

private Timer connectorTimer = null;

public void destroy() {
    connectorTimer.cancel();
    status.stopped();
}
}

I want to test the behavior of destroy that it calls both stopped and cancel. I can test for stopped easily by injecting a mock object of status as below

@Mock
ServiceStatus status;

@InjectMocks
PRCConnectionRunner prcConnection;


@Test
public void destroyShouldCallStatusStop() {
    prcConnection.destroy();
    Mockito.verify(status).stopped();
}

However since i cant inject connectorTimer as it is constructed inside the PRCConnectionRunner class, how can i test that the destroy calls cancel() on connectorTimer?

How to intentionally fail all C# unit tests

QUESTION:

I'm trying to figure out if there's a way to fail all C# unit tests whenever a particular condition is met.

BACKGROUND:

I set up a unit test for an object which encodes and decodes its internal data. Here's a fairly contrived example:

[TestClass]
public class FooTests
{
    private Foo TestFoo { get; set; }

    [TestMethod]
    public void DataEncodingIsWorking()
    {
        // TestFoo.EncodeData() ...
    }

    [TestMethod]
    public void DataDecodingIsWorking()
    {
        // TestFoo.DecodeData() ...
    }

    public FooTests(dynamic[] data) {
        TestFoo = new Foo(data);
    }
}

public class Foo {

    public void EncodeData() {
        // encodes Foo's data
    }

    public void DecodeData() {
        // decodes Foo's encoded data
    }

    public Foo(dynamic[] data) {
        // feeds data to Foo
    }
}

Rather than creating a new instance of TestFoo in every [TestMethod] (somewhat repetitive), I created a global TestFoo object in FooTests. If TestFoo fails to instantiate, I'm looking to fail all FooTests unit tests (as encoding/decoding will not work if the object fails to instantiate).

This isn't really a question of best practices, but I'm also curious as to whether or not this approach is terrible. I suppose another approach would be to set up an additional unit test to see whether or not TestFoo instantiates correctly.

Condense code: SetupSequence returning different values on successive calls

I am testing a method that calls other methods. I have a working test that uses this method to generate my mocked connection object:

    private Mock<IDatabaseConnection> MockOutGetControlDocInfoData()
    {
        Mock<IDatabaseConnection> mockConn = new Mock<IDatabaseConnection>();
        List<Mock<IDbCommand>> mockCmds = new List<Mock<IDbCommand>>();
        List<long> vals = new List<long>() { 2, 2, 2, 2, 10, 2, 2, 2, 2, 2 };
        foreach (long val in vals)
        {
            mockCmds.Add(CreateMockCmdObjectWithReturnValue(val));
        }
        mockConn.SetupAllProperties();
        mockConn.Setup(c => c.Conn.ConnectionString).Returns("What the heck.");
        mockConn.SetupSequence(c => c.CreateCommand(It.IsAny<string>()))
            .Returns(mockCmds[0].Object)
            .Returns(mockCmds[1].Object)
            .Returns(mockCmds[2].Object)
            .Returns(mockCmds[3].Object)
            .Returns(mockCmds[4].Object)
            .Returns(mockCmds[5].Object)
            .Returns(mockCmds[6].Object)
            .Returns(mockCmds[7].Object)
            .Returns(mockCmds[8].Object)
            .Returns(mockCmds[9].Object);
        return mockConn;
    }

I'm not pleased with the SetupSequence Returns, which seems like it ought to be part of a loop, but I don't know how to put more than one Returns into the SetupSequence. Any idea for improvement?

For now at least, I'm fine with manually creating my list of test values.

It shouldn't be relevant, but I can provide the CreateMockCmdObjectWithReturnValue code if needed.

asp.net core mvc controller unit testing when using TryUpdateModel

In an asp.net core application, I have a pair of controller methods that respond to an Edit action. One for Get, which takes a string parameter for the entity id:

public async Task<IActionResult> Edit(string id)

and the other for receiving a post of updated entity values:

    [HttpPost]
    [ActionName("Edit")]
    [ValidateAntiForgeryToken]        
    public async Task<IActionResult> EditSave(string id)

Inside the postable action method, I call

var bindingSuccess = await TryUpdateModelAsync(vm);

And that works fine.

Now, I'm trying to write a test for this, but am finding that TryUpdateModelAsync requires lots of things from HttpContext and the controller to be fleshed out. I've tried mocking those out, but after looking at the source code for TryUpdateModelAsync, I realize that I'd essentially need to mock everything down to the metadata, which isn't proving to be straightforward.

I'm wondering if perhaps this difficulty is telling me something: TryUpdateModelAsync makes it hard to test, so I should refactor the controller method to not rely on this helper. Instead, I could add another parameter to the method for my viewmodel and decorate it with [FromBody], so the model binding would happen from the post fields when present, but I would be able to pass in a view model when testing. However, I like the TryUpdateModelAsync method, because it does the busy work of merging the post fields into my view model. The other way I can think to accomplish the merging is write my own Merge method. Okay, no big deal, but I'd prefer not to have to do this for each entity (or reinvent the wheel writing a reflection based merger) and really, I'm wondering if I just missed the boat on how to write a unit test against this. I could fire up a whole TestServer, like I do for integration tests, but I'm not sure this is the right direction and feels like I would just be complicating my unit tests further. However, maybe it is justified in this scenario?

I've seen answers that worked with previous versions of .net mvc, where all they needed to do was mock an IValueProvider and attach it to the controller, but in .net core it appears the TryUpdateModelAsync was reworked and requires more moving parts.

In sum, I see three options:

  1. Continue mocking and stubbing out all the pieces that TryUpdateModelAsync needs. This might be a dead end, it seems to be so far.
  2. Use TestServer and make this test from a little higher altitude using an HttpClient
  3. Refactor this method to use [FromBody] on a view model parameter, then write my own merge methods for each entity, there by side stepping TryUpdateModelAsync altogether

These all have their drawbacks, so I'm hoping there's a 4th entry to this list that I don't see because I am ignorant.

Unit testing with Mocha and Momentjs

I have a function that I'm trying to unit test with Mocha that uses moment.

function makeRange(timeagoMinutes) {
  var endDate = moment().toISOString();
  var startDate = moment().subtract(timeagoMinutes, 'm').toISOString();
  return startDate + ',' + endDate;
}

Here is what I have so far, but I'm having trouble figuring out what to do with moment. If I call makeRange(40) and run the tests, the string is different each time.

How can I fake the current time (i.e. moment().toISOString()?

var rewire = require('rewire');
var controller = rewire('../thecontroller.js');
var moment = require('moment');

describe.only('makeRange', function() {
  var makeRange;

  beforeEach(function() {
    makeRange = controller.__get__('makeRange');
  });

  it('should return a string with a start date and end date', function() {
    //
  });
});

TypeError: assertEqual() takes at least 3 arguments (2 given)

I am using python 2.7.6, still my program shows an error.

import assignment3 as a3
import unittest
import numpy as np


class a3Testcase(unittest.TestCase):
    """Test for a3 functions"""
    def func_const(self, x):
        return 1

    def func_linear(self, x):
        return x

    def func_quad(self, x):
        return x**2

    def test_gamma_calc(self):
        """determine the Gamma from gamma distribution
        a to b"""
        self.assertAlmostEqual(a3.gamma_calc(self.func_linear, 0, 2), 2)
        self.assertAlmostEqual(a3.gamma_calc(self.func_quad, 0, 1), 1.0/3)

    # def test_create_vortices(self):
    #     """"""
    #     pass

    def test_cal_gamma_array(self):
        """Find the Gamma at mid point of panels a given gamma distribution"""
        panel_coordinates = np.linspace(0, 1, 1+1)
        self.assertEqual((
            a3.calc_gamma_array(panel_coordinates, self.func_const),
            np.array([1.0])))

if __name__ == '__main__':
    unittest.main()

Traceback (most recent call last):

Result:

File "test_assignment3.py", line 32, in test_cal_gamma_array
    np.array([1.0])))

TypeError: assertEqual() takes at least 3 arguments (2 given)

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)

Import Selenium IDE script as unittest.TestCase and Modify Dynamically

I am writing a program in python that will generate more robust data and reports from Selenium tests. I want to be able to export a test case from Selenium IDE from Firefox, and without modifying that specific exported python file, inject it into my script and allow my script to make modifications such as changing the webdriver (part of the implementation is for a Nagios server, which will use PhantomJS as the driver) and pulling request information and screenshots for reporting (Btw, I know I can change the driver in the IDE template, but it's just an example).

Lets say I have a file exported from the IDE path/to/mytests/search.py:

import...

class Search(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.base_url = 'http://www.example.com'

    def test_search(self):
        driver = self.driver
        driver.get(self.base_url)
        elem = self.driver.find_element_by_name('q')
        elem.send_keys('nagios')
        elem.send_keys(Keys.RETURN)
        assert 'No results found.' not in self.driver.page_source
        driver.get(self.base_url + '/status')
        assert 'OK' in self.driver.page_source

    def tearDown(self):
        self.driver.quit()

I want my script to be able to do this:

python -m my_wrapper mytests.search --url 'http://www.google.com'

Which will somehow import search.py, create a new testcase from it, and allow me to override the setUp/tearDown methods (changing the driver to PhantomJS, modifying the base URL from the sys.argv), and allow for catching errors and writing information related to where a failed test might have stopped (since there are two different URL calls, a screenshot of that page will be exported for wherever the driver is currently at).

I'm thinking something like my_wrapper.__main__:

# get 'mytests.search' from argparse
dirname, module = os.path.split('mytests.search'.replace('.', '/'))
suite = unittest.TestLoader().discover(dirname, pattern='%s.py' % module)

# Modify testcases here <-- THIS IS THE HARD PART
#
# Is there a way to inject the tests into another testCase class?
#
# class BaseClass(unittest.TestCase):
#    def setUp(self):
#        self.driver = webdriver.PhantomJS()
#        ...
#
#    def runTest(self): pass
#
#    def tearDown(self): ...
#
# then...
new_suite = unittest.TestSuite()
for sub_suite in master_suite:  #<-- iterating over the above suite here
    for tests in sub_suite._tests:  #<-- why do you have to do this twice?
        for test_name in tests._tests:
            # This doesn't work but show's my thought process
            mytest = BaseClass(methodName=test_name)
            setattr(mytest, test_func, getattr(tests, test_name))
            new_suite.addTest(mytest)

try:
    result = unittest.TextTestRunner(verbosity=2).run(new_suite)
except (SOME_SELENIUM_ERROR):
    # get the screenshot, save to file <-- don't know how to do this either

Anyway, any help into this would be appreciated. I would really like to keep this code as simple as possible using as much of what's available as I can.

Note: Other than selenium and PhantomJS, I'm also wary of using other dependencies like non-standard libraries, etc, for a number of policy reasons. ...

Issue testing null check using NUnit

I am a junior dev that is new to unit testing. My company uses NUnit and I am trying to test a null check in a service method I created. Any idea what my Assert statement should look like if I am trying to test if string acctName = "" ? For some reason string acctName is getting compiler error?

MY METHOD:

public Dict getOrder(Client client)
        {
            string acctName = client != null ? client.AccountName : "";

            Dict replacements = new Replacement
            {
                {COMPANY_NAME, acctName}
        };
            return new Dict(replacements);
        }

MY TEST:

public void getOrderNullTest()
    {

        //Arrange

        Client myTestClient = null;

        //Act

       contentService.getOrder(myTestClient);

        //Assert

        Assert.AreEqual(string acctName, "");

    }

How can I set protected properties of mocks for abstract classes?

I've looked around and I found a solution that works for normal objects, but it doesn't seem to work for mocks.

The test below fails with the message: Property someProperty does not exist.

class sampleTestClass extends PHPUnit_Framework_TestCase
{
    function test() {
        $object     = $this->getMockForAbstractClass(ClassToTest::class, [], '', false);
        $reflection = new ReflectionClass(get_class($object));
        $property   = $reflection->getProperty('someProperty');
        $property->setAccessible(true);
        $property->setValue($object, 'value');
    }
}

abstract class ClassToTest
{
    private $someProperty;
    abstract function someFunc();
}

How do I delay the execution of all unit tests in XCode?

I need my unit tests to wait for our sub-systems to initialize which usually takes a few seconds. In order to wait for this, I can do the following in a test

- (void)testReverseActionWithOffset
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"High Expectations"];

    // Wait for proper initialization of Realm and CrimsonObject system...
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

The problem is, using this technique, I have to do this wait in every single test method. This leads to there being a two second delay between each test even after the system is booted up. Because the test methods run in an undetermined order, I can't put the delay in just one method. What is the correct way to handle this under XCode?

Karma tests failing on code that fixed a previous bug

I made some bug fixes on my code earlier which caused some UI elements to render before data has been loaded completely into the variable. My fix was to render the UI after callback, meaning, data is completely loaded.

Here's the old code:

    @autofindField = (element) =>
      listener = @listeners[element.id]
      availableFields = @elementFields[element.id]
      filterFieldName = listener.field || @filter.field?.name || @filter.dimension
      if listener.on && _.findWhere(availableFields, {name: filterFieldName})
        listener.field = filterFieldName
      else
        delete listener.field

The fixed code:

@autofindField = (element) =>
  listener = @listeners[element.id]
  # Get baseView after autofindField is triggered in order to begin loading of
  # data from the parent directive
  @getBaseView(element.look?.query.model, element.look?.query.view, (baseView) =>
    # On callback, load the option fields, which gets data from the parent directive of baseView
    availableFields = baseView.allFields
    filterFieldName = listener.field || @filter.field?.name || @filter.dimension
    if listener.on && _.findWhere(availableFields, {name: filterFieldName})
      listener.field = filterFieldName
    else
      delete listener.field
  )

The fixed code indeed fixes the issue, however, it seems my Karma tests are failing, and I have no idea why.

Test #1 tests whether autofindField should set field to filter field name:

  it "should set field to filter field name", ->
    $scope.filter =
      title: "Brand Name"
      field:
        name: "products.brand_name"
      name: "Brand Name"
      model: "thelook"
      type: "field_filter"
    $scope.$digest()
    controller.elementFields = {
      2: [{name: "products.brand_name"}]
    }
    controller.toggleListener(elmWithoutLook)
    console.log 'ELM', controller.listeners[elmWithoutLook.id].field
    console.log 'EXP', controller.filter.field.name
    console.log 'LISTENERS', controller.listeners[elmWithoutLook.id]
    console.log 'FILTER', controller.filter
    expect(controller.listeners[elmWithoutLook.id].field).toBe(controller.filter.field.name)

This is the following test:

  it "should set field to filter field name", ->
    $scope.filter =
      title: "Brand Name"
      field:
        name: "products.brand_name"
      name: "Brand Name"
      model: "thelook"
      type: "field_filter"
    $scope.$digest()
    controller.elementFields = {
      2: [{name: "products.brand_name"}]
    }
    controller.toggleListener(elmWithoutLook)
    console.log 'ELM', controller.listeners[elmWithoutLook.id].field
    console.log 'EXP', controller.filter.field.name
    console.log 'LISTENERS', controller.listeners[elmWithoutLook.id]
    console.log 'FILTER', controller.filter
    expect(controller.listeners[elmWithoutLook.id].field).toBe(controller.filter.field.name)

When I run the test, I get the following error:

LOG: 'ELM', undefined
LOG: 'EXP', 'products.brand_name'
LOG: 'LISTENERS', Object{on: true}
LOG: 'FILTER', Object{title: 'Brand Name', field: Object{name: 'products.brand_name'}, name: 'Brand Name', model: 'thelook', type: 'field_filter'}
Chrome 52.0.2743 (Mac OS X 10.11.6) Dashboard Filter Details dashboardFilterDetailsController autofindField should set field to filter field name FAILED
    Expected undefined to be 'products.brand_name'.

It appears that when EXP attempts to assign to ELM, it fails, as it lacks the field within LISTENERS. However, cross-checking the old buggy code with the new fixed code, I don't really notice any area which would cause such an issue. All I did was load fixed data into baseView and assign it into availableFields.

Another possible explanation to this is that the tests are out of date, and was written for the broken code, and thus should be invalidated.

Would love some additional eyes on this..

CppUTest Unit Testing Framework Multiple Definition Exception

I will try to make this a purely minimal example to be as applicable to as many people as possible as well as protect any sort of code sharing that might violate an NDA. Hope this is okay!

I am using CppUTest and CppUMock (compiling with gcc/g++ and makefiles created with CMake) in conjunction with Gitlab Continuous Integration software to create a unit testing environment for future commits and release of software. However, I have run into a bit of a problem. Let's say I have the following folder setup (that I have minimal ability to change, other than the contents of the /tests folder):

+-- src
    +-- driver1.c
    +-- driver2.c
+-- inc
    +-- driver1.h
    +-- driver2.h
+-- tests
    +-- test_driver1.cpp
    +-- test_driver2.cpp
    +-- main.cpp
    +-- cmakelists.txt

The CMakeLists file will contain including of the inc folder, compilation of the src folder, and compilation of the tests folder. However, let's say that driver2.c relies on methods defined by driver1.c. This is fine if there is no mocking setup because you can just test the results of calls to driver2's methods normally. However, say that I want to mock driver1's method1 function so that I can check that driver2 calls method1 correctly (using CppUMock). This would usually be fine, if driver1 wasn't being compiled, but adding something like so to the test_driver2.cpp file:

void method1(int n) {
    mock().actualCall("method1").withParameter("n", n);
}

Will cause a collision with the actual method1 in driver1.c with a linker error like so:

CMakeFiles/http://ift.tt/2c0QURP: multiple definition of 'method1'
CMakeFiles/http://ift.tt/2c8Wij0: first defined here

I'm happy to add details as requested.

What is the best way to get around this mocking issue?

How to mock readline.on('SIGINT')?

I have this piece of code:

function getMsg() {
  return new Promise(function (resolve, reject) {
    var input = [];
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    rl.on('line', function (cmd) {
      if (cmd.trim()) {
        input.push(cmd);
      } else {
        rl.close();
      }
    });
    rl.on('close', function () {
      rl.close();
      resolve(input.join('\n'));
    });
    rl.on('SIGINT', reject);
  });
}

I'm trying to test this function, my attempt, so far, is this:

it('should reject if SIGINT is sent', function () {
  sandbox.stub(readline, 'createInterface', function () {
    return {
      on: function (action, callback) {
        callback();
      },
      prompt: function () {},
      close: function () {}
    };
  });

  return getMsg().then(null).catch(function () {
    expect(true).to.be.equal(true);
  });
});

But of course, that doesn't simulate a SIGINT, how do I do this?

Jasmine test for Angular service does not resolve deferred call

I'm pretty new to Angular and I am working to test an Angular service that runs off an API level service which wraps a bunch of calls to a REST service. Because it is working with HTTP requests, both parts of the service are working with promises and it seems to work fine, but I am having trouble getting any tests of promised behaviour working.

The relevant part of my service code ( grossly simplified ) looks like this:

angular.module('my.info')
 .service('myInfoService', function (infoApi, $q) {
    infoLoaded: false,
    allInfo: [],
    getInfo: function () {
        var defer = $q.defer();
        if (infoLoaded) {
            defer.resolve(allInfo);
        } else {
            infoApi.getAllInfo().then(function (newInfo) {
                allInfo = newInfo;
                infoLoaded = true;
                defer.resolve(allInfo);
            });
        }
        return defer.promise;
    }
});

When I am setting up my mock I have something like this:

   describe("Info Service ",
     function() {
        var infoService, infoRequestApi, $q;
        beforeEach(module("my.info"));
        beforeEach(function() {
            module(function($provide) {
                infoRequestApi = {
                   requestCount: 0,
                   getAllInfo: function() {
                       var defer = $q.defer(); 
                       this.requestCount++;
                       defer.resolve( [ "info 1", "info 2" ] );
                       return defer.promise;
                   }
                };
                $provide.value("infoApi", infoRequestApi);
            });
            inject(function( _myInfoService_, _$q_ ) {
                 infoService = _myInfoService_,
                 $q = _$q_;
            });
        });

        it("should not fail in the middle of a test", function(done) {
            infoService.getInfo().then( function(infoResult) {
                  // expectation checks.
                  expect( true ).toBeTrue();
              }).finally(done);
        });
   });

Any synchronous tests pass fine, but when I try to run any tests like this I get a message saying: Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

It seems as though something about the way that Angular.Mocks handles the deferred result is causing it to fail. When I step through the test, the mock object's defer variable is being set correctly, but the then statement in the service is never called. Where am I going wrong?

How to exclude/disable a specific auto-configuration in Spring boot 1.4.0 for @DataJpaTest?

I am using the @DataJpaTest from Spring for my test which will then use H2 as in memory database as described here . I'm also using Flyway for production. However once the test starts FLyway kicks in and reads the SQL file. How can I exclude the FlywayAutoConfiguration and keep the rest as described here in spring documentation in order to let Hibernate create the tables in H2 for me?

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepository triggerRepository;
}

How can I unit test a method using a datetime?

I have the follow class and method:

class DateTimeHelper(object):

    @staticmethod
    def get_utc_millisecond_timestamp():
        (dt, micro) = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
        return "%s.%03d" % (dt, int(micro) / 1000)  # UTC time with millisecond

How can I unit test it? I am completely stumped although this is simple. It's my first unit test.

Visual Studio 2015 Unit Test IntelliTrace Results

Where would I find the results saved by IntelliTrace for a unit test in Visual Studio 2015? I checked IntelliTrace in the testsettings file, but can't figure out where I should look to see anything IntelliTrace captured.

I found some links like this video (https://www.youtube.com/watch?v=C6hl8txBGcc), but the "View Test Results" option doesn't seem to exist in VS2015.

Thanks for any help!

enter image description here

enter image description here

PHPUnit - End to End testing with code coverage

I am actually trying to track my code coverage with PhpUnit.

After following the basic instruction from documentation and few tutorials, I make it work...

Sadly my tests (49 tests, 100% passing) for all CRUD features of my webservice's models, gives me an average of ... 0% coverage.

My test policy is End to End : A test execute a curl request to the WebService and expect an HTTP response (assert on HTTP Code value, response content and so on).

Both tests and webserver are hosted localy.

This is my phpunit.xml

    <?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://ift.tt/ra1lAU"
         xsi:noNamespaceSchemaLocation="http://ift.tt/2bJbO5J"
         bootstrap="config.php"
         backupGlobals="false"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="Users">
            <directory>
                ./tests/1-UsersSuite
            </directory>
        </testsuite>
        <testsuite name="Catalogs">
            <directory>
                ./tests/2-CatalogsSuite
            </directory>
        </testsuite>
        <testsuite name="Subscriptions">
            <directory>
                ./tests/3-SubscriptionsSuite
            </directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">controllers</directory>
            <directory suffix=".php">models</directory>
        </whitelist>

        <blacklist>

        </blacklist>
    </filter>
</phpunit>

enter image description here

enter image description here

I successfully built a similar test environment with node and Istanbul (Istanbul was running the Server to generate the code coverage report)

With my php stack it's quite different, request are passing from nginx -> php-fpm compiled with xdebug (I am able to use step-by-step debug feature)

PhpUnit is probably designed for Unit testing... it's probably why I am struggling with my End to End tests.

Thx for your help, best regards.

Testing callback in class with bind(this)

I m building an application TDD based and I m having a trouble dealing with a test when I m trying to bind a function call inside another function :

/**
   * Loads the client trusted strategy from passport
   */
  apply () {
    passport.use(this.name, new passportStrategy.Strategy(this.callback.bind(this)))
  }

I need to test that the passportStrategy.Strategy as been called with the object callback method.

Here's the test I m having :

it('should call the passport.use method with clientTrusted value and a new Passport strategy object', () => {
      const spy = chai.spy()
      const ClientTrustedProxied = proxyquire('./../../../app/business/strategy/ClientTrusted', {passport: {use: spy}})
      const clientTrusted = new ClientTrustedProxied(null, Constants.STRATEGY_CLIENT_TRUSTED)
      clientTrusted.apply()
      expect(spy).to.have.been.called.with(Constants.STRATEGY_CLIENT_TRUSTED, new Strategy(clientTrusted.callback))
    })

The fact is clientTrusted.callback is not the same as this.callback.bind(this) (apparently) so I can't test the equality of the two elements.

But if I remove the bind(), the test is passing green, but my app doesn't work anymore (super js scoping).

I need a solution, or at least some help, to make that test passing green.

NB : the strategy object in the test is the following one :

import { Strategy } from 'passport-oauth2-public-client'

or in the class (because of conflicted names):

import * as passportStrategy from 'passport-oauth2-public-client'

Thanks for you help

JUnit - How many files for testing a single class?

Let's say I have a class MyClass.java and we have to write a tests for it. Some of them will execute once, some of them will execute multiple times.

  1. I prepared two test classes - MyClassTestSingle.java for single tests and MyClassTestMultiple.java for tests with @Parametrized annotation.
  2. I wanted to run them from a single file so there is another class - MyClassTestSuite.java.
  3. In MyClassTestSingle.java and MyClassTestMultiple.java methods I use same parameters with a same values so i started thinking about a class containing these parameters...

But then I realized I wanted to create four classes for testing a single class. So I started looking for some "good practices" how to keep my test classes clean and simple. But found no worthy informations about number of classes I need when writing tests for a situation above.

I started thinking that maybe there is a design problem in my MyClass.java, but for sure there are situations when there is need to make a parametrized and single tests and then pack them into a suite.

Am I wrong? Or maybe I just don't understand something?

how to test function on in controller scope executed by event

function in controller:

$scope.f = function($event){
   $event.preventDefault();
   //logic
   return data;
}

it('should...', function(){
    //fire event and expect data
})

what is right way for fire event?

How do I Mock Methods in a Dependency Class of a Controller

Hello I'll like to Mock the getReviews method of the CommentModel so I can test if its called in the ApiReviewCommentsController Method.

This is my method

class ApiReviewCommentsController extends ApiController
{
    private $commentsModel;

    public function __construct(CommentsModel $commentsModel)
    {
        $this->commentsModel = $commentsModel;
        $this->commentsModel->getReviewComment();

    }
}

This is my test

public function testThatItShouldAddGetAllCommentsForReviewId(){


    $reviewId = 1;


    $commentsModel = $this->getMockBuilder(CommentsModel::class)->getMock();

    $controller = new ApiReviewCommentsController($commentsModel);

    $commentsModel->expects($this->once())
        ->method('getReviewComments')
        ->willReturn(false);

}

This is my error

Expectation failed for method name is equal to <string:getReviewComments> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

Please why is the method not called?

Typescript issue with accessing global namespace functions in jasmine test

So this is a strange one that I have looked all over the internet for and have had no luck. I am adding in tests to a clients website with Jasmine, Chutzpah and Visual Studio 2015, so I am modifying existing code. So this is the issue, I have a client side written entirely in typescript and this makes calls to an API on the server. When I create the test files I cannot access functions in a global namespace. So the file I am trying to test looks like this, we will call this file foo.ts

foo.ts

    namespace foo { 

        export function isANumber(n) {
            !isNaN(parseFloat(n)) && isFInite(n);     
        }  

    }

So this is one function I am trying to test inside foo.test.ts. This is my foo.test.ts file. I keep it in the same folder as the foo.ts just so I could see if it was a file placement issue.

foo.test.ts

/// <reference path="foo.ts" />

    describe("Foo Tests",
    function() {

        describe("Is A Number",
            function () {

                var isANumberTest;
                beforeEach(function () {      
                    isANumberTest= foo.isANumber;
                });
                afterEach(function() {
                    isANumberTest= 'undefined';
                });
                it("should return true if a number",
                    function () {
                        expect(isANumberTest(1)).toBe(true);
                    });

                it("should return false if not a number",
                    function() {
                        expect(isANumberTest('n')).toBe(false);
                    });
            });
     });

So the error I get when the tests run is ReferenceError: 'foo' is undefined and TypeError: Object expected. I can see in the debug that foo is undefined. When I tried wrapping the tests in the global namespace I just get the TypeError: Object expected. I can see that foo is now there but it doesn't have isANumber function in it. I am coming from a C# background into javascript. I am assuming that isANumber hasn't been created yet and that is why the tests can't find it. I am new to typescript, javascript and writing test in them. I am not sure if this is a compile issue and something is missing from a config file or if I am even writing the tests right. Any help would be greatly appreciated!! Let me know if you need more info.

Typescript testing in Jasmine in Visual Studio environment

I have looked for three days straight now, and I have great problems finding a good guide to this setup:

Goal: Unit testing of functions created by developers in our team.

Solution uses Visual Studio 2015 (+ Resharper).

Solution contains Web project, which is an Angular2 based website, with code written in typescript. This typescript is what is supposed to be unit tested.

What I managed to do: Set up Jasmine as separate project in the solution. It works, I can create tests that test themselves (expect(7+1).toBe(8) kind of thing).

What I failed to do: Set up Jasmine to be able to compile .ts stuff on the fly (I guess?), to be able to reference .ts files and test them.

TL;DR: I need help setting up a Visual Studio project, in an already existing Angular2 solution, that will allow me to use Jasmine to unit test typescript files. (Perhaps someone has run across a guide that would help).

Aurelia unit test new class instance

I'm trying to write a unit test for a class in my Aurelia app, as follows:

describe("MyClass", () => {
    let sut;

    beforeEach(() => {
        sut = new MyClass(new S1(), new S2());
    });

    it(('should have default value') => {
        expect(sut.getValue()).toBe('default');
        expect(sut.getValue()).not.toBe('something else');
    });

    it('should set new value', () => {
        let val = 'stack';
        sut.setValue(val);
        expect(let.getValue()).toBe(stack);
        expect(let.getValue()).not.toBe('default');
    });

    it('should not set invalid value', () => {
        let invalidVal = 'invalid value';
        sut.setValue(invalidVal);

        expect(sut.getValue()).toBe('default');
        expect(sut.getValue()).not.toBe(invalidVal);
    });
});

The test fails at 'should not set invalid value' - where expected 'stack' to be 'default'.

How can I set the Timeout for a unit test takes to run in TFS Build Server

Recently we have had an issue where a unit test started to take 20+ minutes to run when on the build server.

I have now fixed that issue but I wondered if there was a way to fail the test when running a CI build on TFS server if a test reaches a certain time limit. I've looked at the Definition in TFS and the only timeout I can configure is the "Build job timeout in minutes" which is for the whole project. Currently this is 60 minutes.

What I am wanting is a "unit test timeout".

Can this be configured in TFS? or do I need to set it in my test settings for the solution?

JUnit android test classinheritance

I have simple Android application with some espresso tests. I want to write some base class so all of my test classes will inherit its @beforeClass and @afterClass methods, but the problem is when I do it like code example below, JUnit doesn't see any tests at al. I got Empty test suite. message. What's the problem?

Code example:

public class RealmTest {
    protected static Realm realm;

    @BeforeClass
    public static void beforeClass() {
        realm = Realm.getDefaultInstance();
        realm.setAutoRefresh(true);
    }

    @AfterClass
    public static void afterClass() {
        realm.close();
    }
}

@RunWith(AndroidJUnit4.class)
public class MainActivityTest extends RealmTest {
    @Rule
    public IntentsTestRule<MainActivity> activityTestRule = new IntentsTestRule<>(MainActivity.class);

    @Test
    public void startedFine() {
        assertNotNull(realm);
        onView(withId(R.id.button)).perform(click());
        intended(hasComponent(new ComponentName(getTargetContext(), EducationActivity.class)));
    }
}

If I'll run all tests, tests from MainActivityTest won't run. Thanks for your help, pls say if some additional info is needed.

#define not replacing function name in C++

I am writing unit tests for some legacy code. The framework that we are using here is the cxxtest. It not that good while mocking functions.

So after some research, I found a workaround. I am using #define for changing the call from original function to mock function. For example, if I want to mock socket function in C, I just define another function mock_socket in my mock.hpp file and include it in the test.hpp file. In my test.hpp I used #define like this, #define socket mock_socket. But it is not replacing function socket with mock_socket. For building, I am using cmake. I think it is something associated with cmake. I am new to cmake. Can anyone tell what is the problem here?

PS: It works fine in a model project I created for the testing purpose. But I didn't use cmake in it.

Read SOAP UI Mock service properties

I'm trying to read a property of a mock service in the script:

the property "contatore"

the script where i'm trying to read the property

but i get always error No such property [..] reading the documentation and here

Do you know how i can archive that? Thanks

What is the correct way of using sinon spy restore or reset?

I have a test suit with mocha, sinon and chai:

describe('general visor methods tests', () => {

    let res, req, next, resSpy, resNext;

    beforeEach(() => {
        res = {};
        next = () => {};
        resSpy = res.json = sinon.spy();
        resNext = next = sinon.spy();
    });
    afterEach(() => {
        resSpy.restore();
        resNext.reset();
    });


describe('get basemap layers from owner model', () => {
    it('should send the basemap provided by the owner model', () => {
        owner.basemap = ['basemap1', 'basemap2'];
        getBaseMapLayersFromConfig(req, res, next);
        //  console.log(resSpy.args[0][0].data);
        expect(resSpy.calledOnce).to.eql(true);
        expect(resSpy.args[0][0].message).to.eql('basemaps correctly found');
        expect(resSpy.args[0][0].data).to.eql(['basemap1', 'basemap2']);
    });

...

if I put resSpy.reset() it works fine. I've read that the reset() function is to reset the state of the spy.

But what i don't understand is that if i put resSpy.restore() then it thows the next error:

TypeError: resSpy.restore is not a function

I don't know what I'm doing wrong or what should be the correct way of using restore.

Also I don't quite know when should i use reset or restore.

JMockit mock not getting destroyed

Have a class TestAccess.java having

static private TestAccess instance = new TestAccess ();
public static TestAccess getTestAccess() {
                returns instance;
            }

For testing a test class A.java used jmockito to mock the getTestAccess method

 new MockUp<TestAccess>() {

    @mock
    TestAccess mockTestaccess;

                @mockit.Mock
                public TestAccess getTestAccess() {
                    return mockTestaccess;
                }
}

In another class B.java i dont want to use mock and call TestAccess.java as follows

TestAccess.getTestAccess()

B.java of run independently the real TestAccess instance is returned and works fine.

However during maven run it fails as even in B.java the TestAccess.getTestAccess() return the mock defined in A.java and not the real instance as expected.

Could anyone guide how can this be resolved.

Thanks

Mock repository used by JPQL query while testing

I want to test CRUD Repository with related JPQL:

@Repository
public interface UserRolesRepository extends CrudRepository<UserRoles, Long> {

@Query("SELECT a.role FROM UserRoles a, UserEntity b WHERE b.username=?1 AND a.id=b.id")
public List<String> findRoleByUserName(String name);
}

My problem is to mock repository related to UserEntity. I've tried to mock methods of user repository, but them seem not to be ever called.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BlogCmsApplication.class)
public class UserRolesRepositoryTest {
@Autowired
UserRolesRepository userRolesRepository;
@Mock
UserRepository userRepository;

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

}

@Test
public void findRoleByUserName() throws Exception {
    UserEntity user = new UserEntity("user467","somepass");
    user.setId(1);
    Mockito.when(userRepository.findByUsername(user.getUsername())).thenReturn(user);
    Mockito.when(userRepository.findOne(user.getId())).thenReturn(user);
    Mockito.when(userRepository.exists(user.getId())).thenReturn(true);


    UserRoles role = new UserRoles(1,"ROLE_USER");
    userRolesRepository.save(role);

    List<String> actualRole;
    actualRole = userRolesRepository.findRoleByUserName(user.getUsername());

    List<String> expectedRole = new ArrayList<>();
    expectedRole.add(role.getRole());

    assertNotNull(actualRole);
    assertEquals(expectedRole,actualRole);

}

With @Autowired works fine but it's not the point. Assertion error is

Expected :[ROLE_USER]
Actual   :[]

Error handling in mocha unit tests

I have mocha tests. I will simplify as possible as I can. I wonder how should I handle the errors in mocha tests. For example, if there is an error in getName, what should I do? How can I throw an error? Or should I use done(error) as;

 it('trial', function(done) {
    getName(function (name, err) {
        if(err){
            done(err); //what should I do here? 
        }else{
            console.log(name);
        }
    });
});

JUnit - Test Class Instantiation with objects in parameters

I am very new to JUnit testing and I am trying to understand how to test the instantiation of an class.

Let us say that I have the following ToyBox class which needs an ArrayList of Toys in order to be instantiated. This list of toys is created on another part of the program, of course, but I do not understand very well where I should create it in order to unit test ToyBox,

ToyBox Class

public ToyBox(ArrayList<Toy> toyList){
    this.toys= toyList;

    for (Toy toy: toyList) {
        checkToy(toy);
    }
}

private void checkToy(Toy toy){
    if (toy.isRed()){
        this.numRed += 1;
    } else {
        this.numBlue += 1;
    }
}
public int getBlues(){
    return this.numBlue;
}

ToyBoxTest

public class ToyBoxTest {

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
    }

Where should I instantiate the ToyBox class in order to perform the getNumBlues() method?

Should it be like this?

public class ToyBoxTest {
    ArrayList<Toy> toyList = new ArrayList<Toy>();
    Toy toy1 = new Toy("blue", "car");
    Toy toy2 = new Toy("red", "bike");
    toyList.add(toy1);
    toyList.add(toy2);

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
        ToyBox box = new ToyBox(toyList);
        assertEquals(1, box.getBlues());
    }

Basically, my question is where and how should I create the arraylist of objects needed to test a class that depends on that created list.

I don't know anything about unit testing and I want to learn the best practices for doing it. Thank you in advance!

mardi 30 août 2016

Unit test for class/method who use real folder and files

(I'm really new to ruby so forgive me if my question sound stupid)

I currently write a rails app and inside it I made a lib. This lib is supposed to scan a folder and retrieve each media (image and videos) and their exif data (using mini_exiftool).

In the meantime, I heard of TDD and how unit-test are a really big deal, So I wanted to try it myself (still far from that).

So…I come to my question (finally): Writing test for simple output seem really easy but since my class is supposed to return a (big) array of hashes of every media with inside: basename ,path and another hash with exif data (list really long).

1/Should I use a "test" folder with some files (some media and some others) ? If yes, where should I put it (the folder) (don't forget this is a lib) ? and I probably need more that one folder test ? Considering that media can be very big it will considerably put some weight to the app)

2/if not, what should I do ?

3/How I can be sure that my written test is correct itself ? (writing true or false in assert is easy but a big return written manually is a source of multiple errors)?

Android instrumented test no tests found

I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class AddressBookKeepingInstrumentedTest {


    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;

    @Test
    public void test_simple() {
        assertEquals(2,1+1);
    }
}

When I run this, I get the following error:

junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Tests ran to completion.

Gradle build passed with success before this. Any ideas why this is happening? Do you need any more info?

Thanks, Regards

C# - Verify mocked (MoQ) property's method was called with part of string as a parameter

I'm using MoQ and C# to mock a public property and I want to know if one of the mock's methods was called with any strings starting with a particular set of characters.

So for example, while I know this works:

mockLogger.Verify(x => x.Information($"Entering {methodName}"), Times.Once);

I'm trying, with the below attempt, to see if mockLogger's Information() method was called with a parameter starting with $"Exception in {methodName} - Error Message: {ex.Message} - StackTrace:"

mockLogger.Verify(x => x.Information($"Exception in {methodName}: " +
                                         $"Error Message: {exceptionMessage} - " +
                                         $"StackTrace: ........"), Times.Once);

Is this not possible? Or is there some sort of workaround?

EDIT:

I've even tried

    mockLogger.Verify(x => x.Information($"Exception in {methodName}: " +
                                         $"Error Message: {exceptionMessage} - " +
                                         $"StackTrace: " + It.IsAny<string>()), 
                                         Times.Once);

but it doesn't seem to work either.

Java Constructor being called multiple times

I'm creating a PokerHand class and using JUnit tests to test it, and for some reason my constructor is called 8 times when I call it in one test method, when I create one PokerHand object.

PokerHand constructor (added a print statement to see how many times it was being called, prints 8 separate times):

//Constructor
public PokerHand (Card cardOne, Card cardTwo, Card cardThree, Card cardFour, Card cardFive) {
    System.out.println("creating hand...");
    //Initialize value array
    value = new int[6];
    //Initialize cards list, add cards, and check for duplicates
    cards = new ArrayList<Card>();

    cards.add(cardOne);
    if (cards.contains(cardTwo)) {
        throw new DuplicateCardException();
    } else cards.add(cardTwo);
    if (cards.contains(cardThree)) {
        throw new DuplicateCardException();
    } else cards.add(cardThree);
    if (cards.contains(cardFour)) {
        throw new DuplicateCardException();
    } else cards.add(cardFour);
    if (cards.contains(cardFive)) {
        throw new DuplicateCardException();
    } else cards.add(cardFive);

    determineValueOfHand();
}

Test case:

    @Test
  public void testFlush() {
      PokerHand a = new PokerHand(D10, DJ, DQ, DK, DA);
  }

I've been staring at a screen for some time and I'm new to JUnit tests and eclipse, so I'm sure I'm just missing a small detail. Any help is greatly appreciated

How to resolve then() promise in Karma(w mocha)

I am trying to test the following component's controller lookup function:

lookup () {
    if (this.index == 1) {
        return this.$http.get('http://ift.tt/fyw30c').then(res => {
            this.index = res.data;
            return res;
        });
    }
}

To test it, this is what I am doing:

 controller.lookup();

It is only executing this line

if (this.find.index == 1) {
        return this.$http.get('http://ift.tt/fyw30c')

and not executing .then(..) promise

I also tried using scope.$digest(); and scope.$apply(); but it still not resolving then promise.

controller.lookup(function(response) {
   console.log(controller.index);
    expect(controller.index).is.equal(1);
    done();
  });

Terminal mock for unit-testing python curses programs?

I am writing an interactive terminal program using Python curses. I'd like to write unit tests for its functionalities such as drawing custom pads, controlling font colors, scrolling, and resizing responses. But after some tries and searches, I couldn't find a way to write such unit tests without actually invoking the terminal; I couldn't find a function in curses to read the content of the screen, either.

Is there a mock terminal for Python curses that serves these unit testing needs?

Phantomjs crashes on Unix Jenkins: Auto configuration failed

I am using phantomjs 2.1.1. And karma-phantomjs-launcher@1.0.1.

I am trying to use karma runner to run phantomjs on Jenkins. The os is Unix.

But it fails due to Auto configuration failed

139631766058784:error:0200100D:system library:fopen:Permission denied:bss_file.c:169:fopen('/etc/ssl/openssl.cnf','rb')

139631766058784:error:2006D002:BIO routines:BIO_new_file:system lib:bss_file.c:174:

139631766058784:error:0E078002:configuration file routines:DEF_LOAD:system lib:conf_def.c:199:**

Anyone is being through this? is it a bug of phantomJs?

Here is the build log:

21:52:25 + npm install
21:52:28 npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
21:52:59 
21:52:59 > phantomjs-prebuilt@2.1.12 install angular-js-karma-unittest-temp/java_ui/node_modules/phantomjs-prebuilt
21:52:59 > node install.js
21:52:59 
21:52:59 PhantomJS not found on PATH
21:52:59 Download already available at /tmp/phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2
21:52:59 Verified checksum of previously downloaded file
21:52:59 Extracting tar contents (via spawned process)
21:53:03 Removing javaui/angular-js-karma-unittest-temp/java_ui/node_modules/phantomjs-prebuilt/lib/phantom
21:53:03 Copying extracted folder /tmp/phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2-extract-1472608379727/phantomjs-2.1.1-linux-x86_64 -> /jenkins/workspace/javaui/angular-js-karma-unittest-temp/java_ui/node_modules/phantomjs-prebuilt/lib/phantom
21:53:03 Writing location.js file
21:53:03 Done. Phantomjs binary available at /jenkins/workspace/javaui/angular-js-karma-unittest-temp/java_ui/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs
22:09:03 [EnvInject] - Injecting environment variables from a build step.
22:09:03 [EnvInject] - Injecting as environment variables the properties content 
**22:09:03 PATH=/var/lib/jenkins/.gvm/bin:/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/pyenv/shims:/usr/local/pyenv/bin:/usr/local/maven-3/bin:/usr/local/bin:/bin:/usr/bin:/opt/fortify/bin:/opt/monit/bin:/var/lib/jenkins/.rvm/bin:$WORKSPACE/java_ui/node_modules/phantomjs-prebuilt/lib/phantom/bin
22:09:03 PHANTOMJS_BIN=$WORKSPACE/java_ui/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs**
22:09:03 
22:09:03 [EnvInject] - Variables injected successfully.
22:09:04 [angular-js-karma-unittest-temp] $ /bin/sh -xe /tmp/hudson616596242528942759.sh
22:09:04 + cd /jenkins/workspace/javaui/angular-js-karma-unittest-temp/java_ui

22:09:04 + node_modules/karma/bin/karma start karma.conf.js
22:09:05 [33m30 08 2016 22:09:05.371:WARN [reporter]: [39mCan not load "coverage", it is not registered!
22:09:05   Perhaps you are missing some plugin?
22:09:05 [32m30 08 2016 22:09:05.481:INFO [karma]: [39mKarma v0.13.22 server started at http://localhost:9896/
22:09:05 [32m30 08 2016 22:09:05.508:INFO [launcher]: [39mStarting browser PhantomJS
**22:09:05 [31m30 08 2016 22:09:05.548:ERROR [phantomjs.launcher]: [39mAuto configuration failed
22:09:05 139631766058784:error:0200100D:system library:fopen:Permission denied:bss_file.c:169:fopen('/etc/ssl/openssl.cnf','rb')
22:09:05 139631766058784:error:2006D002:BIO routines:BIO_new_file:system lib:bss_file.c:174:
22:09:05 139631766058784:error:0E078002:configuration file routines:DEF_LOAD:system lib:conf_def.c:199:**
22:09:05 
22:09:05 [31m30 08 2016 22:09:05.555:ERROR [launcher]: [39mCannot start PhantomJS
22:09:05    

22:09:05 [32m30 08 2016 22:09:05.569:INFO [launcher]: [39mTrying to start PhantomJS again (1/2).
22:09:05 [31m30 08 2016 22:09:05.599:ERROR [phantomjs.launcher]: [39mAuto configuration failed
22:09:05 140579193042720:error:0200100D:system library:fopen:Permission denied:bss_file.c:169:fopen('/etc/ssl/openssl.cnf','rb')
22:09:05 140579193042720:error:2006D002:BIO routines:BIO_new_file:system lib:bss_file.c:174:
22:09:05 140579193042720:error:0E078002:configuration file routines:DEF_LOAD:system lib:conf_def.c:199:
22:09:05 
22:09:05 [31m30 08 2016 22:09:05.601:ERROR [launcher]: [39mCannot start PhantomJS
22:09:05    
22:09:05 [32m30 08 2016 22:09:05.603:INFO [launcher]: [39mTrying to start PhantomJS again (2/2).
22:09:05 [31m30 08 2016 22:09:05.632:ERROR [phantomjs.launcher]: [39mAuto configuration failed
22:09:05 139795129825056:error:0200100D:system library:fopen:Permission denied:bss_file.c:169:fopen('/etc/ssl/openssl.cnf','rb')
22:09:05 139795129825056:error:2006D002:BIO routines:BIO_new_file:system lib:bss_file.c:174:
22:09:05 139795129825056:error:0E078002:configuration file routines:DEF_LOAD:system lib:conf_def.c:199:
22:09:05 
22:09:05 [31m30 08 2016 22:09:05.633:ERROR [launcher]: [39mCannot start PhantomJS
22:09:05    
22:09:05 [31m30 08 2016 22:09:05.637:ERROR [launcher]: [39mPhantomJS failed 2 times (cannot start). Giving up.
22:09:05 Build step 'Execute shell' marked build as failure
22:09:06 Archiving artifacts
22:09:06 No prior successful build to compare, so performing full copy of artifacts
22:09:06 Recording test results
22:09:06 Finished: FAILURE

The damage distrubution between 2 constituents

I know, that the title isn't quite clear, but i don't know how to name it better, therefore i will jump directly to the example.

Given some Unit (npc, bot etc) that has Healh Points(HP) and also Shield Points(SP). The Unit can deal damage as well as can be damaged by other Unit. When one Unit attacks another the damage must be absorbed (some part of that damage should affect the HP, the other SP) For example, Unit has the following stats:

  • HP: 100 000
  • SP: 100 000
  • Damage distribution: 80/20 (80% of the overall damage will affect shields, other 20% will health)

So, let's say Unit received damage about 100 000. After that, the stats should be like this:

  • HP: 80 000
  • SP: 20 000

The question is: How to implement this kind of distribution?

I've done something that works, but it cannot be the final solution, at least because it's does not take into account the remained difference in case where damage were bigger than Shield Points. E.g after 100 000 HP, 100 000 SP and 200 000 DMG our Unit should ended up with 0 HP and 0 SP. My solution works in different way (i.e wrong), so the HP remains 80 000 but SP 0. Thus 100 000 damage points were not even considered. The calculations that i perform stands for:

damage // overall damage
damage_hp = damage * 0.20 // take 20% of the total damage value
damage_sp = damage * 0.80 // take the rest 80%
hp = hp - damage_hp; // dealing appropriate damage
sp = sp - damage_sp; // same here

To handle the cases described above (when damage_sp has bigger value than sp itself), i use if-statment, but i do believe that there is more regular/rational solution to doing this kind of thing, in more mathematical way or something.

I would appreciate any hints.

Unit test C# Asp.Net MVC5 methods GET and POST

If I have one method [HttpGet]Index(), and another [HttpPost] Index() then I can't call the unit test in this way:

 [TestClass()]
public class CalculatorControllerTest
{
    [TestMethod]
    public void Index()
    {
        // Arrange
        CalculatorController controller = new CalculatorController();

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);
    }
}

Index() is going marked red.

How can I alter my request in Unit test?

How to write a junit test for double linked list's insertion in between operation?

I have a double linked list in which i can perform various functions but I want to write JUnit tests to test those functionalities. I have written unit tests for testing operations like inserting node at end and head, but how to write a test for the insertion in between operation?

Thank you :)

Here is the my linked list and Test class

DoubleLinkedList.java

public class DoubleLinkedList {

  Node head;

  public void add(int data) {
      Node newNode = new Node(data);
      if (head == null) {
        head = newNode;
      } else {
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
        newNode.prev = current;
      }
  }

  public void print() {
      Node current = head;
      while (current != null) {
          System.out.print(current.data);
          if (current.next != null)
              System.out.print(" -> ");
          current = current.next;
      }
      System.out.println();
  }

  public int size() {
      int size = 0;
      Node current = head;
      while (current != null) {
          size++;
          current = current.next;
      }
      return size;
  }

  public void addIntoHead(int data) {
      Node newNode = new Node(data);

     if (head == null) {
          head = newNode;
      } else {
          head.prev = newNode;
          newNode.next = head;
          head = newNode;
      }
  }

  public int returnHead() {
      return head.data;
  }

  public void addInMiddle(int prevData, int data) {
      Node current = head;
      while (current != null) {
        if (current.data != prevData) {
            current = current.next;
        } else{
            break;
        }
      }
      Node newNode = new Node(data);
      newNode.next = current.next;
      current.next.prev = newNode;
      newNode.prev = current;
      current.next = newNode;
  }

}

DoubleLinkedListTest.java

import org.junit.Test;
import static org.junit.Assert.*;

public class DoubleLinkedListTest {

  private DoubleLinkedList dll;

  @org.junit.Before
  public void setUp() throws Exception {
      dll = new DoubleLinkedList();
  }

  @Test
  public void shouldBeAbleToCreateANewNode() throws Exception {
      int initialSizeBeforeAdd = dll.size();

      dll.add(1);
      dll.add(2);

      assertEquals(initialSizeBeforeAdd+2,dll.size());
  }

  @Test
  public void shouldAbleToAddIntoHead() throws Exception {
      dll.add(1);
      dll.add(2);

      dll.addIntoHead(12);

      assertEquals(0,dll.returnHead());
  }

  @Test
  public void shouldAbleToAddDataInMiddle() throws Exception {
      dll.add(1);
      dll.add(2);
      dll.add(4);
      int size = dll.size();

      dll.addInMiddle(2,3);

    //what should be the assertion here.
  }
}

how to pass types into test method

How can I pass types into my unit tests?

public void MethodUnderTest()
{
    try
    {
        var businessService = _businessService.DoWork();
    }
    catch (SomeException exception)
    {
        //do some stuff
    }
    catch (SomeOtherException exception)
    {
        //do other stuff
    }
}


My unit test should be something like this:

[TestCase(typeof(SomeException))]    
[TestCase(typeof(SomeOtherException))]
public void UnitTest(Exception exception)
{
   _businessService.Setup(x=>x.DoWork).Throws.InstanceOf<exception>();
   //verify that when we called DoWork, that the logic inside of one of the catches was executed
}

Unit Test using cassandra-unit run in intellij but crash when run on command line via sbt

I'm trying to run my unit test via sbt on the command line but every time I get this error.

java.lang.NoSuchMethodError: org.apache.cassandra.utils.FBUtilities.getNetworkInterface(Ljava/net/InetAddress;)Ljava/lang/String;
    at org.apache.cassandra.net.MessagingService.getServerSockets(MessagingService.java:556)
    at org.apache.cassandra.net.MessagingService.listen(MessagingService.java:488)
    at org.apache.cassandra.net.MessagingService.listen(MessagingService.java:472)
    at org.apache.cassandra.service.StorageService.prepareToJoin(StorageService.java:832)
    at org.apache.cassandra.service.StorageService.initServer(StorageService.java:727)
    at org.apache.cassandra.service.StorageService.initServer(StorageService.java:613)
    at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:349)
    at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:551)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper$1.run(EmbeddedCassandraServerHelper.java:125)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
3126 [pool-6-thread-1] ERROR org.apache.cassandra.service.CassandraDaemon  - Exception encountered during startup
java.lang.NoSuchMethodError: org.apache.cassandra.utils.FBUtilities.getNetworkInterface(Ljava/net/InetAddress;)Ljava/lang/String;
    at org.apache.cassandra.net.MessagingService.getServerSockets(MessagingService.java:556)
    at org.apache.cassandra.net.MessagingService.listen(MessagingService.java:488)
    at org.apache.cassandra.net.MessagingService.listen(MessagingService.java:472)
    at org.apache.cassandra.service.StorageService.prepareToJoin(StorageService.java:832)
    at org.apache.cassandra.service.StorageService.initServer(StorageService.java:727)
    at org.apache.cassandra.service.StorageService.initServer(StorageService.java:613)
    at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:349)
    at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:551)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper$1.run(EmbeddedCassandraServerHelper.java:125)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Where as when I run in intellij it runs just fine.

Below is the dependency tree I got from the command line with relevant lib. Couldn't post the whole tree here. Way too much. Any ideas?

 +-org.cassandraunit:cassandra-unit:3.0.0.1
[info]   | +-com.google.guava:guava:18.0
[info]   | +-io.netty:netty-handler:4.0.27.Final (evicted by: 4.0.33.Final)
[info]   | +-io.netty:netty-handler:4.0.33.Final
[info]   | | +-io.netty:netty-buffer:4.0.33.Final
[info]   | | | +-io.netty:netty-common:4.0.33.Final
[info]   | | | 
[info]   | | +-io.netty:netty-codec:4.0.33.Final
[info]   | | | +-io.netty:netty-transport:4.0.33.Final
[info]   | | |   +-io.netty:netty-buffer:4.0.33.Final
[info]   | | |     +-io.netty:netty-common:4.0.33.Final
[info]   | | |     
[info]   | | +-io.netty:netty-transport:4.0.33.Final
[info]   | |   +-io.netty:netty-buffer:4.0.33.Final
[info]   | |     +-io.netty:netty-common:4.0.33.Final
[info]   | |     
[info]   | +-junit:junit:4.12 (evicted by: 4.6)
[info]   | | +-org.hamcrest:hamcrest-core:1.3
[info]   | | 
[info]   | +-junit:junit:4.6
[info]   | +-org.apache.cassandra:cassandra-all:3.4
[info]   | | +-com.addthis.metrics:reporter-config3:3.0.0
[info]   | | | +-com.addthis.metrics:reporter-config-base:3.0.0
[info]   | | | | +-org.apache.commons:commons-lang3:3.1 (evicted by: 3.4)
[info]   | | | | +-org.apache.commons:commons-lang3:3.4
[info]   | | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | | +-org.yaml:snakeyaml:1.11
[info]   | | | | 
[info]   | | | +-io.dropwizard.metrics:metrics-core:3.1.0 (evicted by: 3.1.2)
[info]   | | | +-io.dropwizard.metrics:metrics-core:3.1.2
[info]   | | | | +-org.slf4j:slf4j-api:1.6.4 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.10 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | | +-org.slf4j:slf4j-api:1.7.5 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | | 
[info]   | | | +-org.apache.commons:commons-lang3:3.1 (evicted by: 3.4)
[info]   | | | +-org.apache.commons:commons-lang3:3.4
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | +-org.yaml:snakeyaml:1.11
[info]   | | | 
[info]   | | +-com.boundary:high-scale-lib:1.0.6
[info]   | | +-com.clearspring.analytics:stream:2.5.2 (evicted by: 2.7.0)
[info]   | | +-com.clearspring.analytics:stream:2.7.0
[info]   | | +-com.github.jbellis:jamm:0.3.0
[info]   | | +-com.google.guava:guava:18.0
[info]   | | +-com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap..
[info]   | | +-com.googlecode.json-simple:json-simple:1.1
[info]   | | +-com.ning:compress-lzf:0.8.4 (evicted by: 1.0.3)
[info]   | | +-com.ning:compress-lzf:1.0.3
[info]   | | +-com.thinkaurelius.thrift:thrift-server:0.3.7
[info]   | | | +-com.lmax:disruptor:3.0.1
[info]   | | | +-junit:junit:4.6
[info]   | | | +-org.apache.thrift:libthrift:0.9.2
[info]   | | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | | 
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | 
[info]   | | +-commons-cli:commons-cli:1.1 (evicted by: 1.2)
[info]   | | +-commons-cli:commons-cli:1.2
[info]   | | +-commons-codec:commons-codec:1.10
[info]   | | +-commons-codec:commons-codec:1.2 (evicted by: 1.10)
[info]   | | +-io.dropwizard.metrics:metrics-core:3.1.0 (evicted by: 3.1.2)
[info]   | | +-io.dropwizard.metrics:metrics-core:3.1.2
[info]   | | | +-org.slf4j:slf4j-api:1.6.4 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.10 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.5 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | 
[info]   | | +-joda-time:joda-time:2.4 (evicted by: 2.9.4)
[info]   | | +-joda-time:joda-time:2.9.4
[info]   | | +-net.java.dev.jna:jna:4.0.0
[info]   | | +-net.jpountz.lz4:lz4:1.3.0
[info]   | | +-org.antlr:antlr-runtime:3.5.2
[info]   | | +-org.antlr:antlr:3.5.2
[info]   | | | +-org.antlr:ST4:4.0.8
[info]   | | | | +-org.antlr:antlr-runtime:3.5.2
[info]   | | | | 
[info]   | | | +-org.antlr:antlr-runtime:3.5.2
[info]   | | | 
[info]   | | +-org.apache.cassandra:cassandra-thrift:3.4
[info]   | | | +-com.carrotsearch:hppc:0.5.4
[info]   | | | +-com.github.rholder:snowball-stemmer:1.3.0.581.1
[info]   | | | +-com.googlecode.concurrent-trees:concurrent-trees:2.4.0
[info]   | | | +-de.jflex:jflex:1.6.0
[info]   | | | | +-org.apache.ant:ant:1.7.0
[info]   | | | |   +-org.apache.ant:ant-launcher:1.7.0
[info]   | | | |   
[info]   | | | +-net.mintern:primitive:1.0
[info]   | | | +-org.apache.commons:commons-lang3:3.1 (evicted by: 3.4)
[info]   | | | +-org.apache.commons:commons-lang3:3.4
[info]   | | | +-org.apache.thrift:libthrift:0.9.2
[info]   | | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | | 
[info]   | | | +-org.slf4j:jcl-over-slf4j:1.7.19
[info]   | | | | +-org.slf4j:slf4j-api:1.7.19 (evicted by: 1.7.21)
[info]   | | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | | 
[info]   | | | +-org.slf4j:jcl-over-slf4j:1.7.7 (evicted by: 1.7.19)
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | 
[info]   | | +-org.apache.commons:commons-lang3:3.1 (evicted by: 3.4)
[info]   | | +-org.apache.commons:commons-lang3:3.4
[info]   | | +-org.apache.commons:commons-math3:3.2 (evicted by: 3.4.1)
[info]   | | +-org.apache.commons:commons-math3:3.4.1
[info]   | | +-org.apache.thrift:libthrift:0.9.2
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | 
[info]   | | +-org.caffinitas.ohc:ohc-core:0.4.2
[info]   | | | +-com.google.guava:guava:18.0
[info]   | | | +-net.java.dev.jna:jna:4.0.0
[info]   | | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | | 
[info]   | | +-org.codehaus.jackson:jackson-core-asl:1.9.13
[info]   | | +-org.codehaus.jackson:jackson-core-asl:1.9.2 (evicted by: 1.9.13)
[info]   | | +-org.codehaus.jackson:jackson-mapper-asl:1.9.13
[info]   | | | +-org.codehaus.jackson:jackson-core-asl:1.9.13
[info]   | | | 
[info]   | | +-org.codehaus.jackson:jackson-mapper-asl:1.9.2 (evicted by: 1.9..
[info]   | | +-org.eclipse.jdt.core.compiler:ecj:4.4.2
[info]   | | +-org.fusesource:sigar:1.6.4
[info]   | | +-org.mindrot:jbcrypt:0.3m
[info]   | | +-org.slf4j:jcl-over-slf4j:1.7.19
[info]   | | | +-org.slf4j:slf4j-api:1.7.19 (evicted by: 1.7.21)
[info]   | | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | | 
[info]   | | +-org.slf4j:jcl-over-slf4j:1.7.7 (evicted by: 1.7.19)
[info]   | | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | | +-org.slf4j:slf4j-api:1.7.21
[info]   | | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | | +-org.xerial.snappy:snappy-java:1.1.1.7
[info]   | | +-org.yaml:snakeyaml:1.11
[info]   | | 
[info]   | +-org.apache.commons:commons-lang3:3.1 (evicted by: 3.4)
[info]   | +-org.apache.commons:commons-lang3:3.4
[info]   | +-org.hamcrest:hamcrest-core:1.3
[info]   | +-org.hamcrest:hamcrest-library:1.3
[info]   | | +-org.hamcrest:hamcrest-core:1.3
[info]   | | 
[info]   | +-org.slf4j:slf4j-api:1.7.12 (evicted by: 1.7.21)
[info]   | +-org.slf4j:slf4j-api:1.7.21
[info]   | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.21)
[info]   | 
[info]   +-org.scalamock:scalamock-scalatest-support_2.11:3.2.2 [S]
[info]   | +-org.scalamock:scalamock-core_2.11:3.2.2 [S]
[info]   | | +-org.scala-lang:scala-reflect:2.11.5 (evicted by: 2.11.8)
[info]   | | +-org.scala-lang:scala-reflect:2.11.8 [S]
[info]   | | 
[info]   | +-org.scalatest:scalatest_2.11:2.2.4 (evicted by: 2.2.6)
[info]   | +-org.scalatest:scalatest_2.11:2.2.6 [S]
[info]   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.2 (evicted by: 1.0.4)
[info]   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.4 [S]
[info]   |   +-org.scala-lang:scala-reflect:2.11.7 (evicted by: 2.11.8)
[info]   |   +-org.scala-lang:scala-reflect:2.11.8 [S]

Test with anotation @DataJpaTest - EmbeddedDatabaseType is required

I want to create test with in memory DB using Spring Boot 1.4.RELEASE. When I added anotation @DataJpaTest to the test and executed the test I'm getting following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: EmbeddedDatabaseType is required; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: EmbeddedDatabaseType is required

My Spring boot properties:

spring.jpa.database=ORACLE
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=validate

spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.url=..
spring.datasource.username=..
spring.datasource.password=..

spring.datasource.max-active=20
spring.datasource.max-idle=5
spring.datasource.min-idle=1
spring.datasource.initial-size=5


spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 20000
#spring.datasource.test-on-borrow=true
spring.datasource.validation-query=select 1 from dual;

spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.cache.use_second_level_cache=false

Dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>args4j</groupId>
    <artifactId>args4j</artifactId>
    <version>2.33</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-remote-shell</artifactId>
</dependency>

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

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

<dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3.0</version>
</dependency>

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-core</artifactId>
    <version>1.4.18</version>
</dependency>
<dependency>
    <groupId>org.perf4j</groupId>
    <artifactId>perf4j</artifactId>
    <version>0.9.16</version>
</dependency>
<dependency>
    <groupId>io.reactivex</groupId>
    <artifactId>rxjava</artifactId>
    <version>1.0.13</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>

I was expecting that this annotation will replace my real DB with in memory DB.

Karma coverage always coming empty

I've been trying to run karma coverage for a couple of days now only to find an empty blank page as below. Karma coverage empty report

Here's my configuration:

var path = require('path');

var webpackConfig = require('./webpack.common');

module.exports = function (config) {
  var _config = {
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      { pattern: './karma-shim.js', watched: false }
    ],
    exclude: [],
    preprocessors: {
      './karma-shim.js': ['webpack', 'sourcemap', 'coverage']
    },
    client: {
      captureConsole: false
    },
    webpack: webpackConfig,

    webpackMiddleware: {
      stats: 'errors-only'
    },

    coverageReporter: {
      dir: 'coverage/',
      reporters: [{
        type: 'json',
        dir: 'coverage',
        subdir: 'json',
        file: 'coverage-final.json'
      }]
    },

    remapIstanbulReporter: {
      src: 'coverage/json/coverage-final.json',
      reports: {
        lcovonly: 'coverage/json/lcov.info',
        html: 'coverage/html',
        'text': null
      },
      timeoutNotCreated: 1000, // default value
      timeoutNoMoreFiles: 1000 // default value
    },

    webpackServer: {
      noInfo: true // please don't spam the console when running in karma!
    },
    reporters: ["mocha", "coverage", "karma-remap-istanbul"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_ERROR,
    autoWatch: false,
    browsers: ['PhantomJS'], // you can also use Chrome

    singleRun: true
  };

  config.set(_config);

};

And here's my karma-shim.js file

Error.stackTraceLimit = Infinity;
require('es6-shim');
require('reflect-metadata');
require('ts-helpers');
require('zone.js/dist/zone');
require('http://ift.tt/2bzdqQw');
require('http://ift.tt/2bD0xlP');
require('http://ift.tt/2bzdzU8');
require('http://ift.tt/2bD0Rkt');

var appContext = require.context('./app', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.setBaseTestProviders(browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);

Any idea what am i missing here? Help much appreciated.

Thanks

how to test setter and getter?

how to test setters and getters?

function someClass(){
   var data;

   this.setData = function(value){
       // some complex logic
   }

   this.getData = function(){
      // some complex logic
   }
}

is it right way for execute setData and getData for test it bouts in one test case?

how to run multiple test cases in junit or testng with different set of test data from csv file

I hope this scenario is bit confused me lot. I want to run a few test cases using junit or testng with different set of data from csv file. The code snippet i have tried is given below but it dint work,

    private static CSVReader csvReader = null;
    @BeforeClass
        public static void setUp() {
            csvReader = new CSVReader(new FileReader(fileName));
        }

    @Test
    public void test1() {
        .......
        .......
        System.out.println(csvReader[0]);
    }

    @Test
    public void test2() {
        .......
        .......
        System.out.println(csvReader[1]);
    }

    @Test
    public void test3() {
        .......
        .......
        System.out.println(csvReader[2]);
    }

    @Test
    public void test4() {
        .......
        .......
        System.out.println(csvReader[3]);
    }

My problem is that i need to use data from each column in different test cases and i need to iterate all the test cases again if i have multiple rows in csv file. I have tried using Theories and Datapoints, but it works in a way that first cases runs with all rows in csv file and its moves to next test case and runs again with all rows in csv.

I want the solution to run test1() with first column of first row, test2() with second column of first row, test3() with third column of first row and test4() with fourth column of first row and then same need to be iterated with second row and so on. Is it possible to iterate the test cases like this ? As far i searched we can iterate a particular test cases in many ways. My question is, is this possible to iterate all the test in a class with one set of data and again reiterate the class with another set of data from csv.

Can we accomplish this using junit or testng? if so, please proved some sample code. Thanks in advance!

Automated testing in web applications

We are developing a very large web application using C# and JavaScript. The majority of our calls in the code are handled with JavaScript on the front-end and the only real back-end work is the SQL server which retrieves the relevant dataset and returns it as a JSON object which is then handled once again with JavaScript.

We are currently doing all testing manually with our testers who verify the page functionality against the design specifications to make sure the software is working as expected.

I would love to be able to add some automated testing to the application. I've looked into Unit Testing and it seems that it works a lot better if you have a lot of C# methods with inputs and outputs which are easy to trace and verify that they are working.

What are the standard methods in use in the industry which we can use to verify that the whole application (or at least a majority of it) is working properly?

The sort of things I want to check are:

  1. We have an input page which lets you create a user. This input page should update, let's say, 5 tables in the database. I am adding 10 different pages which allow me to create users in the application, how can I verify that all of those pages are inserting correctly and working properly?

  2. I have a page where I can click a button which inserts a row into the database. How can I check that it's outputting correctly in all the different places it should output?

Off the top of my head, I cannot think of all the different cases I need to check but there are a huge number of them. As far as I have understood, any visual errors can only be tested by users who are manually testing.

I am looking for some feedback on what the best methods are and also how they can be applied to our type of application.

mocking angular test with httpbackend

In a directive, I have a call that takes some time. On that page, to prevent ppl from clicking on the UI elements, we disable the buttons until that call returns.

$scope.isLoading = true;
userService.getUser(true).then((user) => {
// some business logic
$scope.paidUser = true;
$scope.isLoading = false;
});

Then for a button it would be something like this:

$scope.buttonDisabled = $scope.isLoading || $scope.paidUser;

The states of the buttons in my directive also depend on other things like which elements are already selected in the UI. Do I write my unit test and just set $scope.isLoading = false? Like in the unit test, I want the scenario where my service already returned and it's no longer loading any more.

how to test variables in angular services

angular.module('myApp').factory('someService', function(){
    var foo = {}; // can not get access to this variable

    function setData(data){
        foo.data = data;
    }

    function getData(data){
        return foo.data;
    }

   return {
       getData: getData,
       setData: setData
   }
})

how to test this two functions for set and get some data from local variable in service?

describe('someService', function () {
    var someService,
        foo ;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_someService_) {
        someService= _someServicee_;
    }));

    it('should return bundle id', function () {
        expect(someService.setData('test')) // foo.data toBe 'test'
    });
});

how to get access to foo var in service?

$httpBackend.expectGET() without URL still captures request

Doing AngularJS unit tests using the $httpBackend service. For some reason $httpBackend.expectGET('') or $httpBackend.expectGET() seem to be working like a catch-all for the request coming from the tested code i.e. Karma says the test passes with SUCCESS.

More precisely, if I mock the backend with:

$httpBackend.expectGET('').respond(200,'all good');

The tested angular code that makes the $http.get('specific/url/here') call will get captured by this empty `$httpBackend.expectGET('').

I know it is this one that catches the request because if I instead mock the backend with:

$httpBackend.expectGET('bad/url/here').respond(200,'all good');

then Karma FAILs with message:

Error: Unexpected request: GET specific/url/here
Expected GET bad/url/here

Is that expected behavior?

I don't see something relevant in the docs.