mardi 30 août 2016

How to mock a class that is constantly changing?

I have a class [XrmServiceContext][1], and it changes each time the CRM configuration changes.

My service class accepts it in its constructor:

public class fooService(XrmServiceContext xrmServiceContext)
{
   //implementation
}

I need to mock XrmServiceContext in order to set up expectations and verify behavior for my unit tests.

How do I mock this class in order to define behavior in my tests for fooService?

How can I 'force' ALL karma test to fail if an eslint error is found?

I have found that sometimes people do not realise they have linting errors in their tests when they run them since they are show before the test progress/information.

Is there any configuration which will cause ALL tests to fail if any of the tests have any linting errors?

I am using mocha with karma.

Thanks.

Is there an alternative result for Python unit tests, other than a Pass or Fail?

I'm writing unit tests that have a database dependency (so technically they're functional tests). Often these tests not only rely on the database to be live and functional, but they can also rely on certain data to be available.

For example, in one test I might query the database to retrieve sample data that I am going to use to test the update or delete functionality. If data doesn't already exist, then this isn't exactly a failure in this context. I'm only concerned about the pass/fail status of the update or delete, and in this situation we didn't even get far enough to test it. So I don't want to give a false positive or false negative.

Is there an elegant way to have the unit test return a 3rd possible result? Such as a warning?

Angular2 Unit Test With Router

Using 2.0.0-rc.4 at the moment, trying to unit test a component that contains the router. The way I used to handle the router doesn't seem to work anymore and I'm getting some strange errors when I try to run my tests. Has anyone managed to get the router injected unit tests working in rc.4 or should I wait until I have fully upgraded my app to rc.5 and fix it then?

My Code:

describe('Component', () => {
    let activatedRoute: ActivatedRoute;
    let component: Component;
    let router: Router;

    beforeEach(() => {
        addProviders(() => [
            Component,
            provide(Router, { useValue: jasmine.createSpyObj('Router', ['navigate'] })
        ]);
    });

    beforeEach(inject([ Component, Router, ActivatedRoute ], (_component, _router, _activatedRoute) => {
        component = _component;
        router = _router;
        activatedRoute = _activatedRoute;
    });

    describe('On Initialisation', () => {

        it('should return true (dummy test)', () => {
            expect(true).toBe(true);
        });

    });
});

When I run this test, it gives me the following error in my powershell:

_instantiateProvider@D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:29099:38 <- webpack:///~/@angular/core/src/di/reflective_injector.js:636:0
 _new@D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:29088:42 <- webpack:///~/@angular/core/src/di/reflective_injector.js:625:0
get@D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:29049:31 <- webpack:///~/@angular/core/src/di/reflective_injector.js:586:0
D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:38201:75 <- webpack:///~/@angular/core/testing/test_injector.js:55:46
map@[native code]
execute@D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:38201:33 <- webpack:///~/@angular/core/testing/test_injector.js:55:0
D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:38295:63 <- webpack:///~/@angular/core/testing/test_injector.js:149:28
_instantiate@D:/Dev/BPO-Starter-Pack/config/spec-bundle.js:29225:98 <- webpack:///~/@angular/core/src/di/reflective_injector.js:76

Version Information:

Typescript: 1.8 Angular: 2.0.0-rc.4 npm: 3.10.6 node: 6.4.0

How to check boolean getter with AssertJ?

It looks very cool

assertThat(yoda).is(jedi);

until you don't know what is yoda and jedi. But suppose

yoda instanceof Person

where

interface Person {
    boolean isJedi();
}

Then how actually check isJedi with AssertJ?

In conventional JUnit I would write

assertTrue( yoda.isJedi() );

but what in AssertJ?

How to test java code (the source itself)

I have two files in my maven project which belong to each other. One is java code in src/main/java, the other is a json file in src/main/resources folder.

I want to make sure that if a property is added or updated in the Java code, that also the according json file is updated and vice versa. My idea is to write a unit test which fails in such cases.

For most properties I could scan the java code using reflection, but when it comes to generics (for example a property of type List<Foo>) I'm stuck because even reflection does not know about Foo.

So my idea is to parse the java source itself. I've never done this before and don't know what to search for.

How do you mock a return value from PyMySQL for testing in Python?

I'm trying to set up some tests for a script that will pull data from a MySQL database. I found an example here that looks like what I want to do, but it just gives me an object instead of results:

<MagicMock name='pymysql.connect().cursor[38 chars]152'>

Here is the function I am using (simple.py):

import pymysql

def get_user_data():
    connection = pymysql.connect(host='localhost', user='user', password='password',
                                 db='db', charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        sql = "SELECT `id`, `password` FROM `users`"
        cursor.execute(sql)
        results = cursor.fetchall()
finally:
    connection.close()

return results

And the test:

from unittest import TestCase, mock
import simple

class TestSimple(TestCase):

    @mock.patch('simple.pymysql', autospec=True)
    def test_get-data(self, mock_pymysql):
        mock_cursor = mock.MagicMock()
        test_data = [{'password': 'secret', 'id': 1}]
        mock_cursor.fetchall.return_value = test_data
        mock_pymysql.connect.return_value.__enter__.return_value = mock_cursor

        self.assertEqual(test_data, simple.get_user_data())

The results:

AssertionError: [{'id': 1, 'password': 'secret'}] != <MagicMock name='pymysql.connect().cursor[38 chars]840'>

I'm using Python 3.51