dimanche 31 mai 2015

Unit testing app extensions iOS8 via framework

So referring to this answer here it is recommended by apple to put all your code in a framework so you can test it.

So my questions are does this have to be an embedded framework or can you create a separate project and put all the extension code in there?

My concern is because upon creating an extension it comes with an info.plist file and an entitlements file and i am unsure where i should be putting those in relation to the framework and such.

Also once you have made the separate or embedded framework project, how do you set the host for your test? mine is mostly interested in the host app being photos, but saying that i need the actual storyboard to load that derives from SLComposeServiceViewController. So would you create an app delegate target that you can set as the host, and then have that load the MainInterface.storyboard of your extension to start the testing?

OCMock test category methods

I may not completely understand mocking as I have a burning question about a very basic scenario. How does one test an instance method of a class OR how does one test a category method for a class?

Consider a class PeerMessage which defines a few properties, etc. I create my own custom category for PeerMessage called Type where I define a method, isTextMessage:. isTextMessage returns a boolean value based on the contents of a PeerMessage. (Please not that this is just an sample type.)

In a test with OCMock, I configure a mock of type PeerMessage and set it's content to some valid value as follows:

id peerMessage = [OCMockObject mockForClass:[PeerMessage class]];
[[[peerMessage stub] andReturn:@"<valid>"] content];

And then assert that peerMessage is a text message:

XCTAssert([peerMessage isTextMessage]);

Considering how mocking works, this results in: 'Unexpected method invoked'. Clearly, as I didn't specify that I was expecting it; neither did I stub it. As I just wanted to verify this API.

How does one test these instance methods (in this case, category instance methods). One way to do this is to redesign the category as follows:

Instead of

- (BOOL)isTextMessage;

do:

+ (BOOL)isTextMessage:(PeerMessage *)message;

But this is to me is very unnatural and I don't feel like writing this code although I don't see anything wrong with it. It doesn't need to be class method. :/

(If my explanation for the question is a bit ambiguous, I'd be happy to update.)

Testing multiple classes with 1 test

Say I have an interface with 2 classes that both implement it. So we have interface I, with classes A and B. For these 2 classes, we need to test the same implemented function, doSomething() with JUnit4. There's some dependencies, so we're using Mockito. An example test looks like:

@Mock private dependantClass d;

@Test
public void test() {
    A.doSomething();
    verify(d).expectedBehavior();
}

I've written the test suite for A (4 tests), no problems. However, now I have to restructure the test suite so I can execute the same test class on both A and B objects. For this, I should use a parallel class hierarchy.

This has left me stumped. I've tried using the @Parameters annotation, but this gives me the error that I have too many input arguments. I've tried making a super test class that both ATest and BTest extend from, but I'm guessig I'm not doing it right because I get nullpointer exceptions.

Actually copying all test cases and just changing A to B passes all the tests, that's to say that these 2 classes do the same. I realize that that sounds like faulty design, and to be honest, it probably is. However, I do not have the possibility to actually alter the code, I just have to test it.

Am I just doing things wrong? How should I implement this?

What is the best way to write unit test cases for repository methods in an ASP.NET WEB API project?

We are working on a project where ASP.NET web api is used on the server side and angular js is used on client side.

Web API project is designed to use entity framework with repository pattern for data access.

Now I have to start writing unit test cases on all the controller methods. One way I am thinking of achieving this is to mock repository and test remaining part of controller. That looked reasonable but I strongly feel writing unit test cases on the repository methods is also as important as the other. I can't think of any idea how I can write unit test cases on repository methods. I remember to have worked with sqllite by creating in memory database instance to achieve the same couple of years back. Is that way go forward or is there something we can do with less effort.

Any guidance or thoughts ?

How to inject a test application module with RoboGuice using Android's default test framework

With Roboblectric, you can extend RobolectricTestRunner and override getTestLifecycleClass() to easily hook into the lifecycle of the test suite. This easily allows you to force RoboGuice to use whatever test modules you want, without the need to subclass individual test case classes.

The prepareTest method is especially useful in the next example:

An Example with Robolectric:

public class RobolectricTestRunnerWithInjection extends RobolectricTestRunner {

    public RobolectricTestRunnerWithInjection(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    @Override
    protected Class<? extends TestLifecycle> getTestLifecycleClass() {
        return TestLifeCycleWithInjection.class;
    }

    public static class TestLifeCycleWithInjection extends DefaultTestLifecycle {

        private MyApplication application;

        @Override
        public Application createApplication(Method method, AndroidManifest appManifest, Config config) {
            application = (MyApplication) super.createApplication(method, appManifest, config);
            return application;
        }

        @Override
        public void prepareTest(Object test) {
            Module testApplicationModule = new TestApplicationModule();

            if (test instanceof AbstractModule) {
                testApplicationModule = Modules.override(testApplicationModule).with((AbstractModule) test);
            }

            RoboGuice.overrideApplicationInjector(application, RoboGuice.newDefaultRoboModule(application), testApplicationModule);
            RoboGuice.getInjector(application).injectMembers(test);
            MockitoAnnotations.initMocks(test);
        }
    }
}

Is there a similar way to do this using Android's default test suite (http://ift.tt/1FjTxBa)?

I would prefer not to subclass test case classes (i.e. AndroidTestCase, ApplicationTestCase, etc).

How do I test my Camel Route if I have a choice operation?

If I have a Camel route that has implemented a Content based Routing EIP(Choice operation). How do I test it. I'm new to Camel. So, I'm unsure how to do it. I have mentioned a sample code below that has to be tested.

public void configure() throws Exception 
{   
    onException(Exception.class).handled(true).bean(ErrorHandler.class).stop();

    from("{{input}}?concurrentConsumers=10")
    .routeId("Actions")
        .choice()
            .when().simple("${header.Action} == ${type:status1}")
                .bean(Class, "method1")
            .when().simple("${header.Action} == ${type:status2}")
                .bean(Class, "method2")
            .when().simple("${header.Action} == ${type:status3}")
                .bean(Class, "method3")
            .otherwise()
                .bean(Class, "method4")
        .end();       
}

}

Thanks, Gautham

Project Test raise an error when I added the reference to Arduino Project

I have two projects in my Visual Studio Community 2013 solution.

I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:

LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

What is the entry point for Arduino project?

It does not generate any file like a dll or main file?

What can I do to solve this error?

UPDATE

I also tried this configuration in the Arduino Project but I get the same error:

Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

Typhoon: how to inject class instead of instance

I have a third-party library which is written in Swift. The library provides a class that has some class methods in it. Using Typhoon, I want to inject the class into one of my classes so that, under unit testing, I could inject a mock class that provides fake class methods. I'm new to Typhoon and I went though the documentation, but haven't figured out how to do it. Is this even doable with Typhoon?

Karma + Angular undefined error

I just started angular testing with karma and jasmine. I've written two basic tests. One of the two tests pass, but the other one is failing. I can't seem to debug it. I've been looking everywhere, and it should work according to various tutorials. The $scope variable should be available. I get the following error (and a lot of text, see screenshot):

           at C:/totalflatline-2.0/public/lib/angular/angular.js:4362
           at forEach (C:/totalflatline-2.0/public/lib/angular/angular.js:336)
           at loadModules (C:/totalflatline-2.0/public/lib/angular/angular.js:4364)
           at createInjector (C:/totalflatline-2.0/public/lib/angular/angular.js:4248)
           at workFn (C:/totalflatline-2.0/public/lib/angular-mocks/angular-mocks.js:2409)
           at C:/totalflatline-2.0/public/lib/angular-mocks/angular-mocks.js:2392
           at C:/totalflatline-2.0/public/shared/tests/unit/shared.client.controller.unit.tests.js:
5
           at C:/totalflatline-2.0/node_modules/karma-jasmine/lib/boot.js:126
           at C:/totalflatline-2.0/node_modules/karma-jasmine/lib/adapter.js:171
           at http://localhost:9876/karma.js:210
           at http://localhost:9876/context.html:83
       TypeError: 'undefined' is not an object (evaluating '$scope.test')
           at C:/totalflatline-2.0/public/shared/tests/unit/shared.client.controller.unit.tests.js:
9
           at C:/totalflatline-2.0/node_modules/karma-jasmine/lib/boot.js:126
           at C:/totalflatline-2.0/node_modules/karma-jasmine/lib/adapter.js:171
           at http://localhost:9876/karma.js:210
           at http://localhost:9876/context.html:83
hantomJS 1.9.8 (Windows 7): Executed 2 of 2 (1 FAILED) (0.402 secs / 0.025 secs)

The two tests are as following. The first one passes and the other one gives the above undefined error.

The one that passes:

describe('Testing MEAN Main Module', function() {
    var mainModule;
    beforeEach(function() {
        mainModule = angular.module('mean');
    });
    it('Should be registered', function() {
        expect(mainModule).toBeDefined();
        console.log('Success!');
    });
});

The one that fails:

describe('Testing the Shared Stats controller', function(){
    var SharedController,$scope;

    beforeEach(function(){
        // load the module you're testing.
        module('mean');

        inject(function($rootScope,$controller){
            // create a scope object for us to use.
            $scope = $rootScope.$new();

            SharedController = $controller('shared.StatsController',{
                $scope:$scope
            });
        });
    });
    it('Should contain a user object',function(){
        // User cannot be undefined
        expect($scope.test).toEqual('yoo');
    });

});

The angular controller is looking like this:

// Create the 'shared' controller
angular.module('shared').controller('shared.StatsController', [ '$scope',
    function($scope) {
        $scope.test = 'yoo';
    }
]);

Angular version is 1.4 and the karma dependencies are versions:

"karma": "~0.12.23",
"karma-jasmine": "~0.2.2",
"karma-phantomjs-launcher": "~0.1.4",

I have been breaking my neck over this all day. I hope someone with more knowledge about testing angular can help me out.

Visual Studio 2015 Unit Test HTTP localhost

I'm using Visual Studio 2015. Creating a stateful API. Because it's using Sessions I cannot use Unit Testing directly to my Controller classes for validation. I need to use HTTP calls.

But when running my Unit Test it doesn't run my project so the HTTP call doesn't find the url http://localhost:54916/api/register

If I run my project and then goto the menu for running Unit Tests it's disabled.

When running my Unit Tests how can I first run the project so that the web/database is online?

How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

Lets say I am setting a value on the http context in my middleware. For example HttpContext.User.

How can test the http context in my unit test. Here is an example of what I am trying to do

Middleware

public class MyAuthMiddleware
{
    private readonly RequestDelegate _next;

    public MyAuthMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.User = SetUser(); 
        await next(context);
    }
}

Test

[Fact]
public async Task UserShouldBeAuthenticated()
{
    var server = TestServer.Create((app) => 
    {
        app.UseMiddleware<MyAuthMiddleware>();
    });

    using(server)
    {
        var response = await server.CreateClient().GetAsync("/");
        // After calling the middleware I want to assert that 
        // the user in the HttpContext was set correctly
        // but how can I access the HttpContext here?
    }
}

Start Web Dev server before tests start

I'm running Selenium tests. I'd like to be able to start the web server before the tests start, or restart it if it is already running.

  1. Is there a way to achieve this?
  2. Is there a way to control whether the IDE debugger is attached to the web server dependent on whether the tests are run in debug mode or not?

About unit testing, I want to ask that what kind of function/method we can use as unit testing object

I am beginner of unit testing so I want to ask what kind of function/method we can use as unit testing object.

I want unit test sharepoint code which written on C#.

By the way, I don't ask about unit testing framework. I want to know that what kind of function I can use as unit test object.

samedi 30 mai 2015

ReferenceError: Can't find variable: moment

I am doing Unit Tests for a directive. I have the configurations below. The error that I am getting is: ReferenceError: Can't find variable: moment

LOG ERROR

ReferenceError: Can't find variable: moment
updateMonthList@/angular/td-ng-datepicker/src/scripts/datepicker-month-  directive.js:44:20
controller@/angular/td-ng-datepicker/src/scripts/datepicker-month-  directive.js:55:20
invoke@/angular/td-ng-datepicker/src/libraries/angular/angular.js:4182:22
/angular/td-ng-datepicker/src/libraries/angular/angular.js:8441:27
/angular/td-ng-datepicker/src/libraries/angular/angular.js:7693:23
forEach@/angular/td-ng-datepicker/src/libraries/angular/angular.js:331:24
nodeLinkFn@/angular/td-ng-datepicker/src/libraries/angular/angular.js:7692:18
compositeLinkFn@/angular/td-ng-  datepicker/src/libraries/angular/angular.js:7075:23
publicLinkFn@/angular/td-ng- datepicker/src/libraries/angular/angular.js:6954:45
/angular/td-ng-datepicker/test/unit/datepicker-month-directive.spec.js:26:41
invoke@/angular/td-ng-datepicker/src/libraries/angular/angular.js:4182:22
workFn@/angular/td-ng-datepicker/src/libraries/angular-mocks/angular-mocks.js:2350:26
inject@/angular/td-ng-datepicker/src/libraries/angular-mocks/angular-mocks.js:2322:41
/angular/td-ng-datepicker/test/unit/datepicker-month-directive.spec.js:13:15
inject@/angular/td-ng-datepicker/src/libraries/angular-mocks/angular-mocks.js:2321:34
/angular/td-ng-datepicker/test/unit/datepicker-month-directive.spec.js:13:15
Safari 8.0.6 (Mac OS X 10.10.3): Executed 1 of 1 (1 FAILED) (0 secs / 0.538 secs)
Safari 8.0.6

Please advise how I am not able to use a call to a method belonging to module "moment", when I am loading it in the Karma.conf.js?

Karma file

module.exports = function (config) {
config.set({
//  root path location that will be used to resolve all relative paths in  files and exclude sections
basePath: '../',

    // files to include, ordered by dependencies
    files: [

        'src/libraries/angular/angular.js',
        'src/libraries/angular-mocks/angular-mocks.js',
        'src/libraries/jquery/dist/jquery.min.js',
        'src/libraries/jquery-ui/jquery-ui.min.js',
        'src/libraries/lodash/lodash.min.js',
        'src/libraries/angular-route/angular-route.js',
        'src/libraries/angular-resource/angular-resource.js',
        'src/libraries/angular-sanitize/angular-sanitize.js',
        'src/libraries/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'src/libraries/angular-moment/angular-moment.js',
        'src/libraries/angular-translate/angular-translate.js',
        'src/libraries/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
        'src/libraries/angular-ui-sortable/src/sortable.js',
        'src/libraries/ng-teradata/modules/**/*.js',
        'src/scripts/*.html',//load my html
        'test/lib/*.js',
        'test/lib/tmp/*.js',
        'test/lib/tmp/*.tpl.html',//load all my test templates
        'test/unit/*.js',//load all my unit tests
        'src/*.html',
        'src/scripts/*.js'//load all source javascript

    ],
    // files to exclude
    exclude: [],

    // karma has its own autoWatch feature but Grunt watch can also do this
    autoWatch: false,

    // testing framework, be sure to install the correct karma plugin
    frameworks: ['jasmine'],

    // browsers to test against, be sure to install the correct browser launcher plugins
    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Safari'],

    // map of preprocessors that is used mostly for plugins
    preprocessors: {
        'src/**/*.html': ['ng-html2js'],
        'src/*.html': ['ng-html2js']
        //'mock_data/**/*': ['ng-json2js']
    },
    ngHtml2JsPreprocessor: {
        cacheIdFromPath: function(filepath) {
            return filepath.substr(filepath.indexOf('td-ng-datepicker')+8);
            //
            //
        },
        moduleName: 'karmaTemplates',
        stripPrefix: 'src/scripts/'

    },
    // test coverage
    'src/scripts/controllers/*.js': ['jshint', 'coverage'],
    'src/scripts/directives/*.js': ['jshint', 'coverage'],
    'src/scripts/services/app.js': ['jshint', 'coverage'],
    'src/scripts/*.js': ['jshint', 'coverage'],
    reporters: ['progress', 'coverage'],

    logLevel: config.LOG_DEBUG,
    loggers: [{ type: 'console' }],

    // list of karma plugins
    plugins: [
        'karma-*'
    ],
    coverageReporter: {
        // type of file to output, use text to output to console
        type: 'html',
        // directory where coverage results are saved
        dir: 'test/test-results/coverage/'
        // if type is text or text-summary, you can set the file name
        // file: 'coverage.txt'
    },

    junitReporter: {
        outputFile: 'test/test-results/test-results.xml'
    },

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
    })
};

Spec File

'use strict';

describe('Testing the Date Picker Month', function () {
    var $compile, element, $httpBackend, $scope, ctrl, $controller, template,  calendarElement, view;

beforeEach(function () {
    angular.mock.module('td.Datepicker');
});
beforeEach(function () {
    angular.mock.module('ngTemplates');


    inject(function ($injector, _$httpBackend_, $rootScope, _$controller_,   _$compile_, _$rootScope_, $templateCache) {
        $httpBackend = _$httpBackend_;
        view = $templateCache.get('scripts/monthpicker-view.html');
        //prime the templates for use in the unit test
        $httpBackend.whenGET('scripts/monthpicker-view.html').respond(200,   '');
        $templateCache.put('scripts/monthpicker-view.html', view);

        $controller = _$controller_;
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $compile = _$compile_;
        element = angular.element('<div td-datepicker-month></div>');
        template = $compile(element)($scope);
        $scope.$digest();

        ctrl = $controller(template.controller, {
            $scope: $scope
        });
    });
});

afterEach(function () {
});

it('should be true', function () {

    // ctrl.setMonth = jasmine.createSpy();
    //var calendarIcon = element.find('input-group-addon');
    //browserTrigger(calendarIcon, 'click');
    // calendarIcon.triggerHandler('click');
    // expect(ctrl.setMonth).toHaveBeenCalled();
    expect(true).toBe(true);
    });
});

DIRECTIVE

(function () {

'use strict';

angular
    .module('td.Datepicker')
    .directive('tdDatepickerMonth', [DatepickerMonthDirective]);

function DatepickerMonthDirective() {
    return {
        restrict: 'A',
        templateUrl: '', //'scripts/datepicker-month-view.html',
        scope: { month: '=' },
        controller: function ($scope) {
            /*jshint validthis:true */
            var vm = this;

            vm.$controller = undefined;
            vm.monthList = undefined;

            vm.setMonth = function setMonth(month) {
                vm.selectedMonth = month;
                $scope.$emit('selectedMonth', month);
            };

            function updateMonthList() {
                var i;

                var months = [];
                for (i = 0; i < 12; i++) {
                    months.push({
                        name: moment().month(i).format('MMMM').substr(0, 3),
                        value: i + 1
                    });
                }

                vm.monthList = [];
                for (i = 0; i < 3; i++) {
                    vm.monthList.push(months.slice(i * 4, (i * 4) + 4));
                }
            }

            updateMonthList();
            if (!_.isUndefined($scope.month)) {
                vm.setMonth($scope.month);
            }
        },
        controllerAs: 'vm'
     };
   }
})();

Template

<table class="td-datepicker-month">
   <tbody>
       <tr ng-repeat="grouping in vm.monthList">
           <td ng-click="vm.setMonth(month.value)" ng-repeat="month in grouping"  ng-class="{ selected: month.value === vm.selectedMonth }">{{ month.name }}</td>
       </tr>
  </tbody>

Unit Test Cases for Django Admin.py operations

This is my first Django Project. In my admin.py file I have defined fields and search_fields. I am wondering how I can write test cases to validate these.

Code snippet:

class CategoryAdmin(admin.ModelAdmin):
    fields = ['name']
    search_fields = ['name']

Is it required to have unit test cases for these things?

Mockito's spy does not work along with AspectJ using maven

I have the following test class and I'm using Mockito's spy. By running my unit test using Eclipse (right click->Run as unit test) all tests pass which means that eclipse build process using m2e and AJDT works fine.

    @RunWith(MockitoJUnitRunner.class)
    public class SamplelTest {


    @Spy
    @InjectMocks
    private SamplelImpl sampleService = new SamplelImpl() {

        @Override
        public void someMethod() {
           ...
        }
    };


    @Test
    public void someTest() throws Exception {
        sampleService.methodUnderTest();
    }

However when I use maven to run the tests I get the following exception.

    Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.183 sec <<<     FAILURE!
    org.sample.SamplelTest  Time elapsed: 0.182 sec  <<< ERROR!
    org.mockito.exceptions.base.MockitoException: Problems initiating spied field     sampleService
    at     org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:254)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class org.sample.SamplelTest$1
Mockito can only mock visible & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
    ... 25 more
Caused by: org.mockito.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:238)
    at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
    at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
    at org.mockito.internal.creation.cglib.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:57)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
    at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
    at org.mockito.Mockito.mock(Mockito.java:1285)
    at org.mockito.internal.configuration.injection.SpyOnInjectedFieldsHandler.processInjection(SpyOnInjectedFieldsHandler.java:43)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:68)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.relayProcessToNextStrategy(MockInjectionStrategy.java:89)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:71)
    at org.mockito.internal.configuration.injection.MockInjection$OngoingMockInjection.apply(MockInjection.java:93)
    at org.mockito.internal.configuration.DefaultInjectionEngine.injectMocksOnFields(DefaultInjectionEngine.java:20)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.injectMocks(InjectingAnnotationEngine.java:100)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processInjectMocks(InjectingAnnotationEngine.java:62)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:56)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
    ... 25 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.mockito.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:385)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:220)
    ... 44 more
Caused by: java.lang.VerifyError: Cannot inherit from final class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    ... 50 more

What is here the difference between the AJC compiler used in Eclipse with AJDT and my AspectJ maven plugin configuration? Which configuration or phase am I missing here?

Here is my pom.xml:

<dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.6.11</version>
</dependency>
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.4</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
            <executions>
                <execution>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Logging not showing in console during django tests

I am trying some simple tests in django. I have setup my django logging system in my settings file. But when I run my test it won't print debug messages on my console. This happens when I run tests from manage.py test command. If I use my IDE's run command It prints the messages normally. My logging setup is the following

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d (thread)d %(message)s'
        },
        'simple':{
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'console': {
            'level':'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console', ],
            'propagate': True,
            'level': 'DEBUG'

        },
        'payments_system': {
            'handlers': ['console', ],
            'propagate': True,
            'level': 'DEBUG'
        }
    }
}

Logging is based on django's website example. How can I make messages appear in the console when I run tests with manage.py?

Unit testing controllers with ScalaTest in Play! framework

I'm working with Play 2.2 and ScalaTest. It's the first time I'm trying to test a controller in my play application. I do it this way:

class TestArtistController extends PlaySpec with OneAppPerSuite {

  "ArtistController" must {

    "returns artists" in new WithApplication {
      val eventuallyResult = controllers.ArtistController.findNearCity("lyon")(FakeRequest())
      whenReady(eventuallyResult, timeout(Span(2, Seconds))) { result =>
        println(result.body) //it is an Enumerator[Array[Byte]]
        result.header.status mustBe 200
      }
    }
  }
}

It allows me to correctly test the return result but I don't know how to test the body of the result. result.body returns an Enumerator[Array[bytes]] and I totally don't know how I could transform it to retrieve the Json that I'm sending.

What is the good way to do this?

How to inject a service to jasmine

I have the following test case MeetingCtrlSpec.js

describe('ViewMeetingCtrl', function () {
        var $rootScope, scope, $controller   ;

       beforeEach(angular.mock.module('MyApp'));

       beforeEach(inject(function ($rootScope, $controller  ) {
            scope = $rootScope.$new();
            $controller('ViewMeetingCtrl', {
            $scope: scope,
           }); 
        }));

        it('should change greeting value if name value is changed', function () {
            //some assertion
        });
    });

ViewMeetingCtrl.js

(function () {
    'use strict';
    angular.module('MyApp').controller('ViewMeetingCtrl', ViewMeetingCtrl);

    ViewMeetingCtrl.$inject = ['$scope', '$state', '$http', '$translate', 'notificationService', 'meetingService', '$modal', 'meeting', 'attachmentService'];

    function ViewMeetingCtrl($scope, $state, $http, $translate, notificationService, meetingService, $modal, meeting, attachmentService) {
        $scope.meeting = meeting;                    
        //more code goes here
    }
})();

this meeting comes from the app.routes.js file

.state('company.meeting', {
                abstract: true,
                url: '/meetings/:meetingId',
                template: '<ui-view/>',
                resolve: {
                    meeting: function(meetingService, $stateParams){
                        return meetingService
                                .getMeeting($stateParams.meetingId)
                                .then(function(response){
                                    return response.data;
                                });
                    }
                },
            })

My problem is regarding the injection of meeting in this ctrl . I am not sure how to do inject that in my test case. I did like the following .

describe('ViewMeetingCtrl', function () {
            var $rootScope, scope, $controller , meeting   ;

           beforeEach(angular.mock.module('MyApp'));

           beforeEach(inject(function ($rootScope, $controller , meeting     ) {
                scope = $rootScope.$new();
                $controller('ViewMeetingCtrl', {
                $scope: scope,
                meeting : meeting   
               }); 
            }));

            it('should change greeting value if name value is changed', function () {
                //some assertion
            });
        });

... and i got this error Error: [$injector:unpr] Unknown provider: meetingProvider <- meeting

How do i inject meeting dependency to my test case . ?

Unit testing expressjs application

I have the following module that I'm working on adding unit tests for. Basically I want to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), I also want to ensure that app.listen is called with the correct port.

function WebService(express, logger) {
    this.express = express;
    this.log = logger;
    this.port = 3000;
}

// init routes and start the server
WebService.prototype.start = function start() {    
    var app = this.express();

    // Setup routes
    app.use('/', this.express.static('www/html'));

    // Startup the server
    app.listen(this.port);

    this.log.info('Starting webserver on port %s', this.port);

};

module.exports = WebService;

If I remove the app.use (replace with a simple app.get) I can get the listen tested by passing this into the constructor in the unit test

var express_stub = function() {
                var tmpObj = {
                    get: function() {},
                    listen: listen_stub // sinonjs stub
                };
                return tmpObj;
            };

When I switch over to using this.express.static in the route, this falls over (expectedly because this.express doesn't define static) I can't quite get my head wrapped around the correct way to deal with this. The this.express() as the constructor is really throwing me. I can't figure out the correct way to mock the calls I want to validate in express.

Why is using static methods not good for unit-testing?

I heard that creating object with static methods is not good for unit-testing. For instance, we have the following hierarchy:

public abstract class Base{

    public static Base createConcrete(){
        return new Concrete();
    }

    public static Base createSuperConcrete(){
        return new SuperConcrete();
    }
}

public class Concrete extends Base { }

public class SuperConcrete extends Base { }

It's better use instance FactoryMethod instead. Why does using static methods cause too much pain in unit tests? Couldn't someone give an example?

vendredi 29 mai 2015

Groovy MockFor demands not acting as expected for stream

I wanted to create a unit test verifying that a stream was closed. My class decorates the stream it receives with DataputStream, which seems to break the mocking demands feature.

void testBadMock() {
    def mockInputClass = new MockFor(InputStream)
    mockInputClass.demand.with {
        close() {}
    }

    def mockInput1 = mockInputClass.proxyInstance()
    mockInput1.close()
    mockInputClass.verify mockInput1 // passes

    def mockInput2 = mockInputClass.proxyInstance()
    new DataInputStream(mockInput2).close()
    mockInputClass.verify mockInput2 // fails
}

I checked the source code for DataInputStream, and as expected, the stream passed into the constructor is the object which it delegates the close() method call to.

def fakeInput = [close: {println 'I was called'}] as InputStream
new DataInputStream(fakeInput).close() // prints 'I was called'

I see no reason why my mock object is not seeing the close() method call.

Why isnt mockito injecting the right response?

I'm trying to use mockito in the following manner.

Here's a part of main class IClient.

public LoginResponse doLogin() {

        WebTarget target = buildTarget();

        MultivaluedMap<String, Object> authHeaders = prepareHeaders();
        Builder buildRequest = buildRequest(authHeaders,target); 
        Response loginRsp = buildRequest
                .post(Entity.entity(" Valid JSON string",
                        MediaType.APPLICATION_JSON_TYPE));
        if(loginRsp == null)
            LOGGER.error("Response was null");// Response is always returned as null.

Here's my test code

@Test
public void testdoLoginPass(){
        Response response = Response.ok().build();
        WebTarget webTarget = inner.buildTarget();
        Builder buildRequest = inner.buildRequest( getMockHeaders(),webTarget);

        when(buildRequest.post(Entity.entity(anyString(),
                MediaType.APPLICATION_JSON_TYPE))).thenReturn(response);
      Assert.assertNotNull(inner.doLogin());

}

I cant seem to figure out why the response is always null. Any thoughts would be greatly appreciated.

The inner is anonmyous inner class object provides corresponding mock values for buildTarget() and buildRequest(). I'm able to see that the right mock values are generated by debugging. Here is the anonymous inner class

inner= new IClient(client, propConfig){
            WebTarget buildTarget(){
                WebTarget target= mock(WebTarget.class);
                LOGGER.error("Returning mock");
                return target;

            }
          Builder buildRequest(final MultivaluedMap<String, Object>  Headers,WebTarget target){
              Builder builder = mock(Builder.class);
              LOGGER.error("Returning mock");
              return builder;
          }
        };

'myApp.controller is not a function' error in Jasmine

I'm getting the following error in the js console log when attempting to assign the controller to 'myCtrl' variable in a jasmine test: 'myApp.controller is not a function'

In the controller itself, the controller is defined as the following and this is what's triggering the error I mentioned:

myApp.controller('myCtrl', ...

And this is how I'm trying to access the controller in my spec file:

beforeEach(function() {
    module('myApp');
});

it('tests the controller', inject(function($controller) {
    var myCtrl = $controller('myCtrl');
}));

Any idea why it's still throwing this error? Seems to be a missing dependency but not sure where..

UnitTesting a function that reads a text file and returns a dict

I want to unit test this function. It opens a file from disk, but I would like the unit test to not rely on external data, and be totally decoupled from the file system.

def instrument_map(map_filename='Instruments.txt'):
    """Maps instrument prefix to filename"""
    with open(map_filename) as f:
        return dict(line.rstrip().split(' ', 1) for line in f)

I've read about mocking and StringIO, but are not able figure out how to go about implementing either of these. Which would be the better approach, and where to start?

The contents of Instruments.txt looks like this:

00 Score
01 SopranoCn
02 SoloCn

integration testing asp.net web api

I am developing an ASP.Net Web Api service for a project i am working on and i wanted to setup NUnit integration tests for my services.

I have TestFixtureSetup which configures Web Api routes, and i have just added OAuth

    [TestFixtureSetUp]
    public void Setup()
    {
        var type = typeof(UpdatesController);

        AppBuilder app = new AppBuilder();
        app.CreatePerOwinContext(CleoDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        OAuthAuthorizationServerOptions oauthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat =
                new CustomJwtFormat("http://localhost:4673/")
        };
        app.UseOAuthAuthorizationServer(oauthServerOptions);

        this._configuration = new HttpConfiguration();
        this._configuration.MapHttpAttributeRoutes();
        this._configuration.Routes.MapHttpRoute(
            "DefaultApi", 
            "api/{controller}/{id}", 
            new { id = RouteParameter.Optional });
        this._configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
            new CamelCasePropertyNamesContractResolver();

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(this._configuration);

        this._server = new HttpServer(this._configuration);

        var customDelegatingHandler = new CustomDelegatingHandler(Constants.AppId, Constants.ApiKey);
        this._server.Configuration.MessageHandlers.Add(customDelegatingHandler);

        this._apiClient = new UpdatesApiClient("http://localhost:4673/", this._server);
    }

The above works and hosts the service for my unit tests to call, because i am creating my database context per owin context i add the following to my base api controller constructor

this._cleoDbContext = this.Request.GetOwinContext().Get<CleoDbContext>();

The issue i face is that this.Request is null when i debug through the unit test (incidentally the unit tests are using HttpClient to connect to the service.

This is the test method

var model = this._apiClient.GetVersionInfo(new Version(1, 0, 0)).Result;

Assert.That(model.LatestVersion == new Version(1, 0, 0));

And this is the api client method

var message = new HttpRequestMessage(HttpMethod.Get, this._apiBaseAddress + "api/updates/info");
message.Content = new ObjectContent(typeof(Version), version, new JsonMediaTypeFormatter());
var response = await this._httpClient.SendAsync(message);

if (response.IsSuccessStatusCode)
{
    return response.Content.ReadAsAsync<VersionInfoModel>().Result;
}

throw new HttpResponseException(response);

I would appreciate any help in understanding what i have missed and understanding why the request object is null in the base api controller

Thanks in advance

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope Error

I am getting this common error Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope with my test case . I know this is a common one , and there are few other threads explaining with solutions . But i really couldn't come up with a answer to my problem . Can anyone point me in the right direction?

ViewMeetingCtrl ,

(function () {
    'use strict';
    angular.module('MyApp').controller('ViewMeetingCtrl', ViewMeetingCtrl);

    ViewMeetingCtrl.$inject = ['$scope', '$state', '$http', '$translate', 'notificationService', 'meetingService', '$modal', 'meeting', 'attachmentService'];

    function ViewMeetingCtrl($scope, $state, $http, $translate, notificationService, meetingService, $modal, meeting, attachmentService) {
        $scope.meeting = meeting;
        $scope.test = "testvalue";
        if (meeting.Status == 'Cancelled')
        {
            $scope.actionButtons = false;
        }
        else
        {
            $scope.actionButtons = true;
        }

        //more code
    }
})();

MeetingCtrlSpec.js

describe('ViewMeetingCtrl', function () {
    var $rootScope, scope, $controller, meetingService;

    beforeEach(angular.mock.module('MyApp'));

    beforeEach(inject(function ($rootScope, $controller, meetingService) {
        scope = $rootScope.$new();
        $controller('ViewMeetingCtrl', {
            meetingService: meetingService,
            '$rootScope' : $rootScope,
            scope: scope
        });       

    }));

    it('should change greeting value if name value is changed', function () {
        //some assertion
    });
});

Error trace :

Firefox 37.0.0 (Windows 8.1) ViewMeetingCtrl should change greeting value if name value is changed FAILED
        Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- ViewMeetingCtrl
        http://ift.tt/1PTmsqX

        minErr/<@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:63:12
        createInjector/providerCache.$injector<@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/ang
ular/angular.js:4015:19
        getService@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:4162:39
        createInjector/instanceCache.$injector<@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/ang
ular/angular.js:4020:28
        getService@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:4162:39
        invoke@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:4194:1
        instantiate@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:4211:27
        $ControllerProvider/this.$get</<@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/an
gular.js:8501:18
        angular.mock.$ControllerDecorator</<@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/node_modules/angular-mo
cks/angular-mocks.js:1878:12
        @C:/Users/dell pc/Documents/Work/MyApp/FLIS.Client.Tests/test/company/MeetingCtrlSpec.js:8:1
        invoke@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/bower_components/angular/angular.js:4203:14
        workFn@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/node_modules/angular-mocks/angular-mocks.js:2436:11
        angular.mock.inject@C:/Users/dell%20pc/Documents/Work/MyApp/WebApiRole/node_modules/angular-mocks/angular-mocks
.js:2407:25
        @C:/Users/dell pc/Documents/Work/MyApp/Client.Tests/test/company/MeetingCtrlSpec.js:6:16
        @C:/Users/dell pc/Documents/Work/MyApp/Client.Tests/test/company/MeetingCtrlSpec.js:1:1
Firefox 37.0.0 (Windows 8.1): Executed 3 of 3 (1 FAILED) (0.094 secs / 0.091 secs)

What are the benefits of asynchronous unit tests?

I'm new to the async/await world and I'm trying to figure out the benefits of writing asynchronous unit tests for async methods. That is, must a unit test for an async method call that async method asynchronously? If it calls the async method synchronously using Task.Run(), what is lost? In the latter case, code coverage isn't impacted as far as I can see.

The reason I'm asking this is because our mocking software (we use TypeMock) can't support async/await. (They say there is a legitimate reason for this lack of support, and I don't disagree with them.) By calling the async methods synchronously in the unit tests, we can workaround this issue. However, I'd like to know whether we are cutting any corner by doing this.

For example, let's say I have the following async method:

public async Task<string> GetContentAsync(string source)
{
    string result = "";
    // perform magical async IO bound work here to populate result
    return result;
}

The following is the ideal unit test which doesn't work:

[TestMethod()]
public async Task GetContentAsyncTest()
{
    string expected = "thisworks";
    var worker = new Worker();
    // ...mocking code here that doesn't work!
    string actual = await worker.GetContentAsync();
    Assert.AreEqual(expected, actual);
}

But this works, and it does provide the code coverage we need. Is this OK?

[TestMethod()]
public void GetContentAsyncTest()
{
    string expected = "thisworks";
    var worker = new Worker();
    // mocking code here that works!
    string actual = Task.Run(() => worker.GetContentAsync()).Result;
    Assert.AreEqual(expected, actual);
}

JMockit: Overriding @Mocked class

I have an internal StreamGobbler class that has 7 methods in it. I'm looking for a quick way to mock all the methods by default, but override one method (e.g. Partial Mocking). It seems like I need to use the @Mocked annotation in combination with MockUp to partially mock the getOutput method.

This is similar to the question JMockit: @Mocke and MockUp combination in the same test, but I can't get away with just looking at method counts.

If I have a test setup like this:

@Test
public void execute(@Mocked StreamGobbler sg)
{
    new MockUp<StreamGobbler>()
    {
        String type = null;

        @Mock
        void $init(String type)
        {
            this.type = type;
        }

        @Mock
        String getOutput()
        {
            if ("OUTPUT".equals(type))
            {
                return "test output";
            }
            else 
            {
                return "";
            }
        }
     }
 }

I get this error java.lang.IllegalArgumentException: Class already mocked

If I try to add the @Override annotation in the MockUp, it doesn't help (and Eclipse complains about it)

What is the best way to handle this? Use a static class outside this test method?

Using JMockit 1.17

java.io.StreamCorruptedException for mocked inputstream

I am mocking the socket class and ObjectInputstream class. Here is a test case which is giving me

java.io.StreamCorruptedException

The test case is as follows:

public void test_tryPush() throws IOException {
        ByteArrayInputStream inside = new ByteArrayInputStream("hey".getBytes());

        Mockito.when(socket.getInputStream()).thenReturn(inside);


        input = new ObjectInputStream(socket.getInputStream());

        assertSame(inside, socket.getInputStream());

}

If I do not delcare the input object of ObjectInputStream class the test passes.

But the test above gives the following trace.

Running tests
Test running started
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2109)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)
at tests.MockingTest.test_tryPush(MockingTest.java:113)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)

Finish

Please can anybody tell me what is going wrong here. I am trying to mock the client side socket.

Minimal JUnit test code to test an AbstractHessianConnection

I am endeavouring to write a unit test to (a) prove a theory of a recent outage; and (b) regression test the fix. What this requires me to do a is create a JUnit class that:

  1. Instantiates a trivial HTTP server (within the same JVM as the JUnit test case is running) which simply returns "403 Forbidden" responses accompanied by a simple error message string.
  2. Instantiates a trivial Hessian service proxy to "talk" to the HTTP server (the service interface is irrelevant since the server is just going to respond to all requests with 403s.
  3. Calls the Hessian service proxy repeatedly.

How can I do this in a relatively small number of lines of code? Examples appreciated!

Grails - JSONBuilder - Spec toPrettyString() returns stackoverflow

I m making a unit test that needs to return a Json. To build that json i m using toPrettyString() method from JSONBuilder.

This is the class to spec:

class Lugar {
String sigla
String nombre
Coordenada coordenada

String toString(){
    "${sigla}"
}

String toJson()
{
    new JsonBuilder( this ).toPrettyString()
}

static constraints = {
    nombre blank: false , nullable: false
}
}

The spec to run is this:

@TestFor(Lugar)
class LugarSpec extends Specification {

void "toJson not empty"() {

    when:
    Lugar lugar = new Lugar(sigla: "BUE", nombre:"BUENOS AIRES")
    String aux = lugar.toJson();

    then:       
    ! aux.dump().empty

}
}

But the result is:

 <error type="java.lang.StackOverflowError">java.lang.StackOverflowError
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at groovy.lang.MetaBeanProperty.getProperty(MetaBeanProperty.java:60)
    at groovy.lang.PropertyValue.getValue(PropertyValue.java:40)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:287)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)

And it continues repeating until the end.

I tried to test toJson on a main and the results were fine:

    static void main(String[] args) {
    Lugar lugar = new Lugar(sigla: "BUE", nombre:"BUENOS AIRES")

    String aux = lugar.toJson();

    println aux.dump()
}

The results were:

{
"sigla": "BUE",
"constraints": {
    "nombre": {
        "blank": false,
        "nullable": false
    }
},
"nombre": "BUENOS AIRES"
}

Well i'd really appreciate i m trying to make some TDD and i m new on Grails.

Thanks.

How to add and retrieve items to and from mock repository with Rhino Mocks

Why does this test fail? How do you add and retrieve items from a mock repository?

[TestMethod]
public void Can_Mock_Sales_Force_Repo()
{
    // arrange
    var salesForcePolicyRepo = MockRepository.GenerateMock<IRepository<SalesForcePolicy>>();

    // act
    var salesForcePolicy = new SalesForcePolicy { PolicyNumber = "123456" };
    IEnumerable<SalesForcePolicy> salesForcePolicies = new List<SalesForcePolicy> { salesForcePolicy };
    salesForcePolicyRepo.Stub(x => x.FindByExp(null)).IgnoreArguments().Return(salesForcePolicies.AsQueryable());

    // assert
    Assert.IsTrue(salesForcePolicyRepo.Contains(salesForcePolicy));
}

The FindByExp method is in the base interface.

public interface IRepository<T> : IReadOnlyRepository<T> where T : class
{
    void EnrollInUnitOfWork(IUnitOfWork unitOfWork);
    IQueryable<T> FindBy(Func<T, bool> predicate);
    IQueryable<T> FindBy(Func<T, bool> predicate, params Expression<Func<T, object>>[] includes);
    void Add(T item);
    void Add(IEnumerable<T> items);
    void Remove(T item);
    void Remove(IEnumerable<T> items);
    void Update(T item);
    int Execute(string command, params object[] parameters);
    IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters);
    void Attach(T item);
}

public interface IReadOnlyRepository<T> where T : class
{
    int Count { get; }
    bool Contains(T item);
    IQueryable<T> FindAll();
    IQueryable<T> FindAll(params Expression<Func<T, object>>[] includes);
    IQueryable<T> FindByExp(Expression<Func<T, bool>> predicate);
    IQueryable<T> FindByExp(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes);
}

How directory structure for Web project (html + css + js + java/spring) should look with javascript Jasmine unit tests?

I am trying to incorporate into my project some Jasmine javascript unit tests. Where should I put it in the source tree? This is my current structure:

projectName/
  css/
  img/
  js/
  index.html (etc)

It should be in this public directory, or outside of it? I will be incorporating this frontend part into a Java Spring project. What should whole structure should look like?

Flask server returns 404 when attempting unit tests

I'm trying to start doing unit testing on my flask app before I add any more functionality, and I've been stuck at the starting line for longer than I'd like to admit. I'm using Flask-Testing (latest master from their repo). I'm also using LiveServerTestCase because I'd like to use selenium live testing. An example of the setup guide was provided on the flask docs website which seemed simple enough.

I have tried so many code variations that have not worked but I'll post the most recent iteration.

Here is the error message that I keep getting:

(venv)username@username-VM64:~/git/approot$ python ./seleniumtests.py
 * Running on http://127.0.0.1:8943/ (Press CTRL+C to quit)
127.0.0.1 - - [29/May/2015 20:01:12] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [29/May/2015 20:01:13] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [29/May/2015 20:01:14] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [29/May/2015 20:01:15] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [29/May/2015 20:01:16] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [29/May/2015 20:01:17] "GET / HTTP/1.1" 404 -
E
======================================================================
ERROR: test_server_is_up_and_running (__main__.BaseTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./seleniumtests.py", line 23, in test_server_is_up_and_running
    response = urllib2.urlopen(self.get_server_url())
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: NOT FOUND

----------------------------------------------------------------------
Ran 1 test in 5.093s

FAILED (errors=1)

This is just the basic server test, and it appears that the app instance doesn't exist even though it looks like its running at the start.

Here is the seleniumtests.py

import urllib2, os, unittest
from app import models, db, app, views
from flask import Flask
from flask_testing import LiveServerTestCase

class BaseTestCase(LiveServerTestCase):

    def create_app(self):
        app = Flask(__name__)
        app.config.from_object('config.TestConfiguration')
        return app

    def test_server_is_up_and_running(self):
        response = urllib2.urlopen(self.get_server_url())
        self.assertEqual(response.code, 200)

    def setUp(self):
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()



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

this is the config i'm using stored in config.py

class TestConfiguration(BaseConfiguration):
    TESTING = True
    DEBUG = True
    WTF_CSRF_ENABLED = False
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
    LIVESERVER_PORT = 8943

This is what my folder structure looks like, if that helps.

.
├── app
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── momentjs.py
│   ├── static
│   ├── templates
│   └── views.py
├── config.py
├── __init__.py
├── README.md
├── requirements
├── run.py
├── seleniumtests.py
├── tmp
│   ├── cover
│   └── coverage
├── unittests.py
└── venv

Any insight would be helpful. I was finally getting the hang of flask (and feeling good about it) until I hit automated testing.

Getting IllegalArgumentException while running test with Spring

I am trying to do test as follow:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { 
  "classpath:test-context.xml"
})
public class EventTest {

  @Autowired private DataSource dataSource;
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  @Test
  public void testEvent(){
    String sql = "select * from event";
    List<Map<String, Object>> resultSet = jdbcTemplate.queryForList(sql);
    System.out.println(resultSet);
  }
}

In test-context.xml I have

<jdbc:embedded-database id="datasource">
    <jdbc:script  location="classpath:schema.sql" />
    <jdbc:script  location="classpath:data.sql" />
</jdbc:embedded-database>

Still I am getting exception

java.lang.IllegalArgumentException: Property 'dataSource' is required
  at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
  at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:165)

Any suggestion?

Access a value set up by `beforeAll` during tests

Here's what I've got:

spec :: Spec
spec = do
  manager <- runIO newManager

  it "foo" $ do
    -- code that uses manager

  it "bar" $ do
    -- code that usees manager

The docs for runIO suggest that I should probably be using beforeAll instead, since I do not need manager to construct the spec tree, I just need it to run each test, and in my use case it's better for them to all share the same manager rather than creating a new one for each test.

If you do not need the result of the IO action to construct the spec tree, beforeAll may be more suitable for your use case.

beforeAll :: IO a -> SpecWith a -> Spec

But I can't figure out how to access the manager from the tests.

spec :: Spec
spec = beforeAll newManager go

go :: SpecWith Manager
go = do
  it "foo" $ do
    -- needs "manager" in scope
  it "bar" $ do
    -- needs "manager" in scope

How to access a Static Class Private fields to unit test its methods using Microsoft Fakes in C#

I have the below static class and a method in it which I need to unit test. I am able to But this method has the if condition which uses a Boolean private variable and if the value of it is false then it executes the steps in that if condition.

public static class Logger
{
    private bool bNoError = true;
    public static void Log()
    {
        if (!bNoError)
        {
            //Then execute the logic here
        }
        else
        {
            //else condition logic here
        }
    }
} 

Is there a way I can set the private field bNoError value to true so that I can have one test method which tests the logic in if condition.

How do I write a Scala unit test to verify that a function is called with some particular function as a parameter?

I have a class:

class SomeDao {
  this: support =>

  def get(id:Long): Option[SomeDto] = {
     support.sprocCall(SomeDto.fromResultSet, SomeDao.getSproc, id)
  }  
}

SomeDto.fromResultSet is actually a Function1 [WrapperResultSet, SomeDto].

Is it possible to verify that support.sprocCall has been called with the correct function as the first parameter?

Visual Studio 2013 Unit tests don't compile - header files not found

I'm testing some c++ code for a homework, and all of the sudden, the concerned header files for code I haven't changed anything in are not being found anymore. I just added one test, and did not change anything in the concerned .cpp en .h files. I get compiling errors, but I really don't have a clue what is happening because nothing changed. I'm not including the code because I think this is irrelevant, but I one thinks I should I will. Is this some known structural problem with the Unit testing module in VS20113? I have searched the net for any similar cases, but haven't found any. If I should address this question somewhere else, please let me know.

$scope.$on is undefined in unit test

I'm unit testing the initialization part of my controller and I can't seem to get over $scope.$on is undefined error. I would like to know how to write the unit test in this case or how to test $scope.$on(). I have failed to find the official angular documentation for testing this.

var SidebarController = function ($rootScope, $scope, $window, $location, PersonService, SearchService) {
    $scope.navName = 'Filters'
    $scope.currentFilter = null;
    $scope.filterResult = null;
    $scope.showFilters = true;
    $rootScope.subTabs = null;

    $scope.$on('userDataLoaded', function () {
        //doing stuff here
    });
    //... more stuff here
}

SidebarController.$inject = ['$rootScope', '$scope', '$window', '$location', 'PersonService', 'SearchService'];

and my test is:

    beforeEach(inject(function (_$controller_, _$rootScope_, _$window_, _$location_, _$httpBackend_, _PersonService_, _SearchService_) {
    $controller = _$controller_;
    scope = _$rootScope_.$new();
    rootScope = _$rootScope_;
    location = _$location_;
    $httpBackend = _$httpBackend_;
    mockWindow = _$window_;
    mockPersonService = _PersonService_;
    mockSearchService = _SearchService_;
    rootScope.userInfo = { tabs: [] };
    scope.$on = function (event, callback) { };
    scope.$digest();
}));

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

it('should set  the initial data', function () {
    $controller('SidebarController', { $rootScope: rootScope, $scope: scope, PersonService: mockPersonService });

    rootScope.$broadcast('userDataLoaded');

    expect(scope).toBeDefined();
    expect(scope.navName).toEqual('Filters');
    expect(scope.currentFilter).toBe(null);
    expect(scope.filterResult).toBe(null);
    expect(scope.showFilters).toBe(true);
    expect(rootScope.subTabs).toBe(null);
});

From what I understand the correct way to do it is to broadcast the event and not spyOn the $scope.$on function itself.

Form model is always undefined while testing

I have a form, bound like this:

<form name="form.card">

which gets validated and accessed in a controller without problems, like this:

$scope.form.card.$setValidity('mycriteria', false);

But when the same controller method is run inside a test, the form is undefined, and so I can't access its validation status. Binding the form on the controller instead that on the scope makes no difference.

Is some kind of initialization missing? Or is this supposed to be like this and I shouldn't meddle with form models?

Thanks in advance.

Jasmine not recognizing spied on method called from asynchronous function resolution

From my controller, upon instantiation, I am calling an asynchronous method that calls a scope method:

app.controller 'MyCtrl', ($scope,mySvc) ->
  ## do some initial stuff
  mySvc.asyncMethod
  .then (an_array) ->
    val = $scope.myScopedMethod

My test is like so:

describe "my tests", () ->
  $controller = undefined
  $scope = undefined
  $q = undefined
  createController = undefined
  mySvc = undefined

  beforeEach inject ($controller, $rootScope, $q, _mySvc_) ->
    $scope = $rootScope.$new()
    mySvc = _mySvc_
    deferred = $q.defer()
    deferred.resolve []
    spyOn(mySvc,'asyncMethod').and.returnValue deferred.promise
    spyOn($scope, 'myScopedMethod').and.callThrough()
    createController = () ->
      return $controller('MyCtrl', {$scope: $scope, mySvc: mySvc})

  # this assertion works
  it "should call asyncMethod", () ->
    controller = createController()
    expect(mySvc.asyncMethod).toHaveBeenCalled()

  # this also works
  it "should define myScopedMethod", () ->
    controller = createController()
    expect(angular.isFunction($scope.myScopedMethod)).toBe true

  # this fails with 'Error: Expected a spy, but got Function.'
  it "should call $scope.myScopedMethod", () ->
    controller = createController()
    $scope.$digest()
    expect($scope.myScopedMethod).toHaveBeenCalled()

I get the same error whether I call $digest() or not. I am expecting $digest() to resolve asyncMethod so that it calls myScopedMethod, but something is not right.

Why does Order matter in Kwarg parameters in MagicMock asserts?

I have a test where I am mocking a filter call on a manager. the assert looks like this:

filter_mock.assert_called_once_with(type_id__in=[3, 4, 5, 6], finance=mock_finance, parent_transaction__date_posted=tran_date_posted)

and the code being tested looks like this:

agregates = Balance.objects.filter(
            finance=self.finance,type_id__in=self.balance_types,
            parent_transaction__date_posted__lte=self.transaction_date_posted
        )

I thought that since these are kwargs, order shouldn't matter, but the test is failing, even though the values for each pair DO match. below is the error I am seeing:

AssertionError: Expected call: filter(type_id__in=[3, 4, 5, 6], parent_transaction__date_posted=datetime.datetime(2015, 5, 29, 16, 22, 59, 532772), finance=) Actual call: filter(type_id__in=[3, 4, 5, 6], finance=, parent_transaction__date_posted__lte=datetime.datetime(2015, 5, 29, 16, 22, 59, 532772))

what the heck is going on? kwarg order should not matter, and even if I do order to match what the test is asserting, the test still fails.

Setting $location.protocol() in angular unit testing

I have a service that checks $location.protocol() and does different things if it's http vs https. How can I set $location.protocol() in unit tests to test my service?

Django.test override_settings() vs modify_settings()

Going off of these docs.

What's the difference between override_settings() and modify_settings()? It seems redundant. The docs say:

It can prove unwieldy to redefine settings that contain a list of values. In practice, adding or removing values is often sufficient. The modify_settings() context manager makes it easy:

Couldn't override_settings() just be written to handle settings that contain a list of values?

Mocking Interface as non-nullable instance with RhinoMocks

I have written a method as suggested in http://ift.tt/1AyDsfw. In short its a method that accepts all kind of Enums as argument and does some basic checking.

public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) 
   {
      throw new ArgumentException("T must be an enumerated type");
   }
   //...
}

Now I want to write a test for this, that validates that when a non Enum time is feed to it, an exception is thrown. I wanted to generate a dummy object as follow with RhinoMocks.

var mock = MockRepository.GenerateMock<IConvertible>();

But the method doesn't accepts the nullable type.

Is there a way to mock structs/non-nullable instances with RhinoMocks?

Spring controller tests with mocks

So i'm having some issues coming up with a solution for a test, here's what i have so far.

This is the method i want to test(i'm new to this) this clears all fields on a web page each time it's loaded.

@RequestMapping("/addaddressform")
public String addAddressForm(HttpSession session)
{
    session.removeAttribute("firstname");
    session.removeAttribute("surname");
    session.removeAttribute("phone");
    session.removeAttribute("workno");
    session.removeAttribute("homeno");
    session.removeAttribute("address");
    session.removeAttribute("email");

    return "simpleforms/addContact";
}

and here's what i have so far for the test package ControllerTests;

import java.text.AttributedCharacterIterator.Attribute;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
   import                   org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
   import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
   import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
   import org.springframework.test.web.servlet.setup.MockMvcBuilders;
   import org.springframework.web.context.WebApplicationContext;

import static     org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


   @RunWith(SpringJUnit4ClassRunner.class)
   @WebAppConfiguration
   @ContextConfiguration (classes = {SimpleFormsControllerTest.class})

public class SimpleFormsControllerTest {
  @Autowired
  private WebApplicationContext wac;
enter code here
  private MockMvc mockMvc;

  @Before
  public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

    @Test
    public void addAddressForm_ExistingContactDetailsInForm_RemovalFromSession()          throws     Exception{

    MockHttpSession mockSession = new MockHttpSession();

    mockSession.putValue("firstname", "test");
    mockSession.putValue("surname", "test");
    mockSession.putValue("phone", "test");
    mockSession.putValue("workno", "test");
    mockSession.putValue("homeno", "test");
    mockSession.putValue("address", "test");
    mockSession.putValue("email", "test");

                  mockMvc.perform(get("simpleForms/addaddressform").session(mockSession));

}

as this is the first time i've ever had to do this kind of thing i really don't have much clue where to go with this.

how can I test a method for greater code coverge in Java?

I seek a method written in Java that tests a method with as greater code coverage as possible. Meaning, I want to know how can I count a number of instructions executed by this method in Java.

How do I do it?

Please provide your practical inputs.

Webtest - missing dll

When I creating webtests I want to add "Web Test Plug-in" I get message box with information that one of my nuget library is missing.

Whole my solution is compilable and this "missing" library exists as entry in csproj and config files. After compilation of test project this library is inside "bIn" folder. I check under dotPeek version, publicToken etc is correct.

My question is where webtest project look for this library?

Unit-testing a functional core of value objects: how to verify contracts without mocking?

I wanted to give the Functional Core/Imperative Shell approach a shot, especially since Swift's structs are so easy to create.

Now they drive me nuts in unit tests.

How do you unit test a net of value objects?


Maybe I'm too stupid to search for the right terms, but in the end, the more unit tests I write, the more I think I should delete all the old ones. In other words my tests seem to bubble up the call chain as long as I don't provide mock objects. Which is impossible for (struct) value objects, because there's no way to replace them with a fake double unless I introduce a protocol, which doesn't work well in production code when methods return Self or have associated types.

Here's a very simple example:

struct Foo {
    func obtainBar() -> Bar? { 
      // ... 
    }
}

struct FooManager {
    let foos: [Foo]

    func obtainFirstBar() -> Bar {
        // try to get a `Bar` from every `Foo` in `foos`; pass the first
        // one which isn't nil down
    }
}

This works well with a concrete Foo class or struct. Now how am I supposed to test what obtainFirstBar() does? -- I plug in one and two and zero Foo instances and see what happens.

But then I'm replicating my knowledge and assertions about Foo's obtainBar(). Well, either I move the few FooTests into FooManagerTests, which sounds stupid, or I use mocks to verify the incoming call instead of merely asserting a certain return value. But you can't subclass a struct, so you create a protocol:

protocol FooType {
    func obtainBar() -> Bar
}

struct Foo: FooType { /* ... */ }

class TestFoo: FooType { /* do some mocking/stubbing */}

When Bar is complex enough to warrant its own unit tests and it seems it should be mocked, you end up with this instead:

protocol FooType {
    typealias B: BarType

    func obtainBar() -> B
}

But then the compiler will complain that FooManager's collection of foos doesn't work this way. Thanks, generics.

struct FooManager<F: FooType where F.B == Bar> {
    let foos: [F]         // ^^^^^^^^^^^^^^^^ added for clarity 

    func obtainFirstBar() -> Bar { /* ... */ }
}

You can't pass in different kinds of Foo, though. Only one concrete FooType is allowed, no weird mixes of BlueFoo and RedFoo, even if both return the same Bar and seem to realize the FooType protocol in the same way. This isn't Objective-C and duck typing isn't possible. Protocols don't seem to add much benefit in terms of abstraction here anyway unless they're not depending on anything else which is a protocol or Self.

If protocols lead to confusion and not much benefit at all, I'd rather stop using them. But how do I write unit tests if one object is mostly a convoluted net of dependent objects, all being value types, seldomly optional, without moving all tests for every permutation in the test suite of the root object(s)?

How to get Moq to verify method that has an out parameter

I have an interface definition where the method has an out parameter defined

public interface IRestCommunicationService
{
    TResult PerformPost<TResult, TData>(string url, TData dataToSend, out StandardErrorResult errors);
}

I have the following class that is using the above interface

    public TripCreateDispatchService(IRestCommunicationAuthService restCommunicationService, ISettings settings)
    {
        _restCommunicationService = restCommunicationService;
        _settings = settings;
    }

    public FlightAlert CreateTrip(string consumerNumber, PostAlertModel tripModel, out StandardErrorResult apiErrors)
    {
        url = .. code ommited
        var result = _restCommunicationService.PerformPost<FlightAlert, PostAlertModel>(url), tripModel, out apiErrors);
        return result;
    }

In my unit tests I am trying to verify that the PerformPost Method of the RestCommunication object is called.

But no matter what I do, I cannot get Moq to verify that the method was called

    public void DispatchService_PerformPost()
    {
        var consumerNumber = ...
        var trip = ...
        var result = ...
        var apiErrors = new StandardErrorResult();
        ... code to setup mock data
        _mockRestCommunicationService = new  Mock<IRestCommunicationAuthService>();
        _mockEestCommunicationService.Setup(x => x.PerformPost<string, PostAlertModel>(It.IsAny<string>(), It.IsAny<PostAlertModel>(), out apiErrors)).Verifiable();


        _systemUnderTest.CreateTrip(consumerNumber, trip, out apiErrors);

        _mockRestCommunicationService.Verify(m => 
            m.PerformPost<StandardErrorResult, PostAlertModel>(
            It.IsAny<string>(), 
            It.IsAny<PostAlertModel>(), out apiErrors
            ), Times.Once);
    }

But I am receiving the following error

Moq.MockException : 

Expected invocation on the mock once, but was 0 times: 
m => m.PerformPost<StandardErrorResult,PostAlertModel>(It.IsAny<String>(), It.IsAny<PostAlertModel>(), .apiErrors)

No setups configured.

How do I go about verifying that the method was called.

I am using Moq and NUnit

Jasmine create a fake object that is globally defined

I have a globally defined function (assume that somewhere in JSP):

var ABC = function (block1, block2) {
// lots of  properties
// lots of functions
}

And also have an angular app and a module:

angular.module('module_name').run(['$rootScope', '$window', function ($rootScope, $window) {
    'use strict';
        $(document).ready(initABC);
    }

    function initABC() {
        $window.ModalWindow = new ABC($('.modal-window'), someOtherParameter);
...
    }

}]);

Code is perfectly working. I want to create a test for it.

ddescribe('Modal directive', function () {
    'use strict';

    var $compile, $rootScope, $window;
    var mod, $scope;

    beforeEach(inject(function (_$compile_, _$rootScope_, _$window_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $window = _$window_;
    }));

    beforeEach(function () {
        compileDirective('<module_name></module_name>');
    });

    describe('Some functionality', function () {

        it('is not shown when some property is not set', function () {
            expect(mod.find('.modal').length).toBe(0);
        });

    });

    function compileDirective(element) {
        mod = AngularTest.compileDirective($rootScope, element);
        $scope = mod.isolateScope();
        $scope.$digest();
    }
});

When compiling directive initABC method is called, which creates new ABC instance. When running the test I am getting following error:

ReferenceError: Can't find variable: ABC
    at initABC

I guess I have to mock it in my test? How can I do it? I have tried a lot of things including spyOn and jasmine.createSpyObj, but nothing helped (maybe I did in a wrong way).

Visual Studio Online: How to create a build definition with MVC Unit Testing that accesses a remote server?

I am currently using:

  • Visual Studio 2013 for development
  • Visual Studio Online for builds/testing
  • MS Build
  • An Azure VM to house an MVC web app and SQL database

The current project is an N-tier MVC application with an MVC Test project. The application runs on the Azure VM (in the cloud), but is accessible locally by being part of the company domain. I have created some unit tests that test the controller actions and they are passing locally. When I check-in and build the project with VSO, the unit test(s) fails with the following error:

Test method Enrollment.StudentEnrollment.Tests.Controllers.HomeControllerTest.SearchWithNoTermOrFilterDefaultSort threw exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I am assuming that this error has to do with VSO not being able to access the VM due to being on a different domain, but could use some help in how to fix the issue. I would like to be able to run my unit test with the build through VSO/TFS.

I am hoping that someone on here has a little more experience than I do with this process and can help me with connecting VSO to the remote server/remote SQL server.

Some ideas that I have, but I am unsure on how to proceed with them at this time:

  • A different connection string format: current data source = vm20150201\apps
  • An MSBuild definition command or setting that I am unaware of?
  • An azure setting to connect the VM and VSO Online site to the the same domain

Thanks

Python: Mock doesn't work inside celery task

I want to use python mock library for testing that my Django application sends email.

Test code:

# tests.py
@mock.patch('django.core.mail.mail_managers')
    def test_canceled_wo_claiming(self, mocked_mail_managers):
        client = Client()
        client.get('/')
        print(mocked_mail_managers.called)
        mocked_mail_managers.assert_called_with('Hi, managers!', 'Message Body')

First example - without tasks

# views.py
from django.views.generic import View
from django.core.mail import mail_managers

class MyView(View):

    def get(self, request):
        mail_managers('Hi, managers!', 'Message Body')
        return HttpResponse('Hello!')

Second example - with tasks

# views.py
from django.views.generic import View
from . import tasks

class MyView(View):
    def get(self, request):
        tasks.notify.apply_async()
        return HttpResponse('Hello!')


# tasks.py
from celery import shared_task
from django.core.mail import mail_managers

@shared_task
def notify():
    mail_managers('Hi, managers!', 'Message Body')

The first example works normal, second example fails, with Not called exception.

My settings:

# Celery
BROKEN_URL = 'memory://'
BROKER_BACKEND = 'memory'

CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'

Is it possible to perform such integrated test or the only way to solve this problem is split test into two?

Run Unit Tests For Play Framework Through Eclipse and Specific Package

Everytime I try to run the External Tools Configuration for the unit tests for a play application, it runs it for ALL tests. I just want to point to the folder I have selected in my project and run those. Is there something I am missing configuration wise in my external tools configuration that can make it generic enough to just select the folder to run the unit tests and run the tool?

enter image description here

How to mock a redis client in Python?

I just found that a bunch of unit tests are failing, due a developer hasn't mocked out the dependency to a redis client within the test. I'm trying to give a hand in this matter but have difficulties myself.

The method writes to a redis client:

redis_client = get_redis_client()
redis_client.set('temp-facility-data', cPickle.dumps(df))

Later in the assert the result is retrieved:

res = cPickle.loads(get_redis_client().get('temp-facility-data'))
expected = pd.Series([set([1, 2, 3, 4, 5])], index=[1])
assert_series_equal(res.variation_pks, expected)

I managed to patch the redis client's get() and set() successfully.

@mock.patch('redis.StrictRedis.get')
@mock.patch('redis.StrictRedis.set')
def test_identical(self, mock_redis_set, mock_redis_get):
    mock_redis_get.return_value = ???
    f2 = deepcopy(self.f)
    f3 = deepcopy(self.f)
    f2.pk = 2
    f3.pk = 3
    self.one_row(f2, f3)

but I don't know how to set the return_value of get() to what the set() would set in the code, so that the test would pass.

Any advice please?

function is not being called with a karma spyOn

My controller is:

window.map.controller('ScheduleHomeController', ['$scope', '$location', '$route', '$routeParams', 'cache', 'patientCache',
    function($scope, $location, $route, $routeParams, cache, patientCache) {

        cache.set('ui', 'headerMessage', '');

        if(cache.get('patient', 'currentPatient').patientId !== $routeParams.patientId) {
            cache.set('patient', 'currentPatient', patientCache.getPatient(parseInt($routeParams.patientId, 10)));
        }

        switch($route.current.originalPath) {
            case '/patients/:patientId/schedule':
                cache.set('ui', 'schedulePage', 'daily-schedule');
                $scope.showScheduleNavbar = true;
                break;
            default:
                $scope.showScheduleNavbar = false;
                break;
        }
    }
]);

My test is:

fdescribe('ScheduleHomeController', function() {
    var scope, cache, $route, patientCache, $routeParams;

    beforeEach(function() {
      module('mapApp');

      return inject(function($injector) {
        var $controller, $rootScope;
        $rootScope = $injector.get('$rootScope');
        $controller = $injector.get('$controller');
        $route = $injector.get('$route');
        cache = $injector.get('cache');
        patientCache = $injector.get('patientCache');
        $routeParams = $injector.get('$routeParams');

        scope = $rootScope.$new()
        $route.current = { originalPath: '/patients/:patientId/schedule' };

        $controller('ScheduleHomeController', {
            $scope: scope,
            cache: cache,
            patientCache: patientCache,
            $route: $route,
            $routeParams: $routeParams
        });

        return scope.$digest();

      });
    });

    it('should set the ui.headerMessage to empty', function() {
        spyOn(cache, 'set');
        expect(cache.set).toHaveBeenCalledWith('ui', 'headerMessage', '');
    });

});

So I expect cache.set to be called, but instead I get Expected spy set to have been called with [ 'ui', 'headerMessage', '' ] but it was never called.

What am I doing incorrectly?

Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information

I have a windows application containing certain unit tests, whenever i try to run or debug any unit test i get the below error in test explorer-

Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..

I'm using Visual studio 2012 premium with the latest update and Code coverage is not enabled. Any help in resolving the issue is highly appreciated.

writing my first database test setting up a fixture

I am writing my first database test using PHPUnit. I am going to make a fixture and test my database with accoring to this link.

anyhow before I do that I wanted to write a simple test, here is my test:

<?php
class MyTest extends PHPUnit_Framework_TestCase
{
    public function testCalculate()
    {
        $this->assertEquals(2, 1 + 1);
    }
}
?>

when I run this using this command: php -f myPHPTest.php

I get the following error:

PHP Fatal error:  Class 'PHPUnit_Framework_TestCase' not found in C:\wamp\www\SV
N\tests\MyPHPTest.php on line 3
PHP Stack trace:
PHP   1. {main}() C:\wamp\www\SVN\tests\MyPHPTest.php:0

Fatal error: Class 'PHPUnit_Framework_TestCase' not found in C:\wamp\www\SVN\tes
ts\MyPHPTest.php on line 3

Call Stack:
    0.0011     234848   1. {main}() C:\wamp\www\SVN\tests\MyPHPTest.php:0

how can I solve this and what do I have to do to write my first database test?

BTEC Grade calculator : No idea how to convert letters into numbers and print out final grade

Right, so basic problem. I'm designing a BTEC grade calculator, for those that are not in the know; BTEC is a type of qualification done in the UK and has a 'different' point grading system mainly based on coursework. There is a number of units (20) and each unit you can get a pass, merit and distinction on each unit. Each pass, merit and distinction add up to so many points and these points add up to the overall grade.

  • BTEC Tariff Info
  • DStar DStar DStar 420
  • DStar DStar D 400
  • DStar DD 380
  • DDD 360
  • DDM 320
  • DMM 280
  • MMM 240
  • MMP 200
  • MPP 160
  • PPP 120

My problem is doing a mock up of a basic letter code print out is that with this BTEC system, I have no idea how to implement it; being a complete beginner at C# but knowing some basics.

Pseudo Code: Whats Your Name: - Name Enter your units: D M P D M P ( And the rest )

Your final grade is DMM

That's essentially what i need it to do is instead of putting 40 for a P I just want to put a P which would = 40 as such. This is my current code but it needs to be changed and fixed.

class Program
{
    static void Main(string[] args)
    {
        int counter;
        double score;

        while (true)
        {
            counter = 1;
            score = 0.0;
            Console.WriteLine("Enter Your Name or type 'exit' to quit): ");
            // Naming for exiting 
            string name = Console.ReadLine();
            if (name == "exit")
            {
                Environment.Exit(0);
            }
            else
            {
                int numberOfUnits = 20;
                Console.WriteLine("Number of Units:  ");
                numberOfUnits = int.Parse(Console.ReadLine());

                while (counter <= numberOfUnits)
                {
                    Console.WriteLine("Final Grade Score {0}", counter);
                    score += double.Parse(Console.ReadLine());
                    counter++;
                }
                // Add up and print letter grade. 
                score = (score / (counter - 1));
                if (score < 120)
                {
                    Console.WriteLine("Letter Grade: PPP");
                }
                else if (score < 160)
                {
                    Console.WriteLine("Letter Grade: MPP");
                }
                else if (score < 200)
                {
                    Console.WriteLine("Letter Grade: MMP");
                }
                else if (score < 240)
                {
                    Console.WriteLine("Letter Grade: MMM");
                }
                else if (score < 280)
                {
                    Console.WriteLine("Letter Grade: DMM");
                }
                else if (score < 320)
                {
                    Console.WriteLine("Letter Grade: DDM");
                }
                else if (score < 360)
                {
                    Console.WriteLine("Letter Grade: DDD");
                }
                    // After DDD it goes up by 20's ..... D* = 20 not 40...
                else if (score < 380)
                {
                    Console.WriteLine("Letter Grade: D*DD");
                }
                else if (score < 400)
                {
                    Console.WriteLine("Letter Grade: D*D*D");
                }
                else if (score < 420)
                {
                    Console.WriteLine("Letter Grade: D*D*D*");
                }
                Console.WriteLine("Grade: {0}", (score).ToString("P"));
            }
        }
    }
}

}