jeudi 30 juin 2016

Failing to stub somewhat complex method calls with Mockito (Scala)

Today, my colleague and myself were fighting with difficulties to stub a method of a dependency in one of out unit tests.

The service class under test looks something like this:

class MongoChecklistResultRepository @Inject()(system: ActorSystem,
                                               reactiveMongoApi: ReactiveMongoApi,
                                               checklistResultVersioningService: ChecklistResultVersioningService)
...
override def count(): Future[Int] = collection(ResultsCollectionName).count()
...

private def collection(name: String): JSONCollection =
    reactiveMongoApi.db.collection[JSONCollection](name)
    }

And inside the test that should test count method, we are trying to mock the collection object that we getting from driver and eventually stub it's count method:

doReturn(Future.successful(1)).when(jsonCollection).count()

All looks valid, but when executed, collection(ResultsCollectionName).count() always retuns null (in simple words the stub is not working.

if we look on the count method os generic collection, we'll see much more complex signature:

def count[H](selector: Option[pack.Document] = None, limit: Int = 0, skip: Int = 0, hint: Option[H] = None)(implicit h: H => CountCommand.Hint, ec: ExecutionContext): Future[Int]

And I beleive, this is the exact reason why the stubbing does not work.

We also tried doing this:

doReturn(Future.successful(1)).when(jsonCollection).count[MockCommand](None, 0, 0, None)

Also, didn't help. How can create reliable stub for these kind of methods?

Thanks,

Testing angular js forms

I had a simple form, something like this

<form class="Form" name="form"> 
  <input type="text">
</form>

But then I had to use two different forms and show them based on some condition. To achieve that, I used ng-if

<form class="Form" name="forms.someForm" ng-if="someCondition()"> 
  <input type="text">
</form>

<form class="Form" name="forms.someForm" ng-if="!someCondition()"> 
  <input type="text">
</form>

and I created an object on controller

$scope.forms = {}

This seems to be working fine now. But this change broke my unit tests. Right now, in unit test spec I have form reference as

scope.form = {}

But when I run Jasmine test, it gives me this error

TypeError: 'undefined' is not an object (evaluating $scope.forms.someForm.$invalid)

Where

$scope.forms.someForm.$invalid

happens to be a part of controller's code.

What change I need to make to the test spec? Can anyone please help?

Spring Best practice for Dependency Injection

I have some confusion about DI in spring

public interface A{
    void methodA();
}
public class AImpl implements A{
    public void methodA(){
          // todo something
    }
}

public interface B{
    void methodB();
}
public class BImpl implements B{
     public void methodB(){
       //todo somethong
     }
}

I have two interface A and B and 2 class implements it. So, I have 2 Class that implement interface C, it depend on Interface A and B

This is case 1:

public interface C{
    void methodC();
}

public class CAutowired implements C{
    @Autowired
    private A a;
    @Autowired
    private B b;

    public void methodC(){
       a.methodA();
       b.methodB();
    }
}

File .xml config

  <beans>
       <bean id="classA" class="com.example.AImpl" />
       <bean id="classB" class="com.example.BImpl" />
       <bean id="classC" class="com.example.CAutowired" />
    <beans>

In this case, i have a question: - How to Mock A and B when i write unitTest for class CAutowired

This is case 2:

public class CInitInject implements C{
    private A a;
    private B b;

    public CInitInject(A a, B b){
       this.a = a;
       this.b = b;
    }

    public void methodC(){
       a.methodA();
       b.methodB();
    }
}

File .xml config

  <beans>
       <bean id="classA" class="com.example.AImpl" />
       <bean id="classB" class="com.example.BImpl" />
       <bean id="classC" class="com.example.CInitInject">
             <constructor-arg ref="classA" />
             <constructor-arg ref="classB" />
       </bean>
    <beans>

In this case, i get DI method the same in .NET. I can Mock A and B by inject into constructor. Example:

@Mock
private A aMock;
@Mock
private B bMock;

private C c;

public void setUp(){
   c = new CInitInject(aMock, bMock);
}

@Test
public void test(){
   // todo Test somemethod
}

End of all, I have a question

  1. What is best practice between case 1 and case 2?
  2. How to Mock it when unit test

Catching a function's error thrown from inner, anonymous function

I have this function:

Item.edit = function(item, newData, done) {
  Item.getUpdatedData(item, newData, function(updatedData) {
     if (this.hasValidData(updatedData)) {
       done(updatedData);
     } else {
       throw "Cannot update item";
     }
  });
}

I want to test that it throws an error under the right circumstances, but when I call the outer function in my test, I get an Unhandled rejection Error in the output (meaning the error is actually thrown), but it doesn't recognize that the function under test actually threw the error.

I'm pretty sure this has to do with the scope where the error is thrown, but I can't figure out how to throw the error from the outer scope of the function.

How do I append Google Test's XML output to an existing XML file?

So Google Test allows you to write output to an XML for logging purposes and possibly for consumption by a Continuous Integration service. I want to take advantage of this facility. Apart from the regular key-value pairs the default xml output provides, the RecordProperty("key",value) function allows a person to append addition user-defined info to the XML output. For example, one property would be (execution_time= 0.56ms). 

What I want to do is to get a time-series of these key-values, that I can later plot using a plugin in a CI to visualize the execution time taken by various tests after various changes. Essentially, I want google test to to append to the same XML file after running each test (each test is determined by its unique timestamp / commit ID / custom parameter). Does google test allow you to do this?

If googletest does not allow to append to an existing XML file, I am thinking of using rapidXML and replicate the same structure of a google test report (conforming to the JUnit format). However, can a JUnit-conformant XML-document consist of more than 1 ? Since each is a complete test run, can I have multiple testsuites in the same XML document and still conform to JUnit (so that Jenkins consumes it easily?)

Typemock unit tests are marked as Ignored

My company is adopting typemock for unit test coverage. In the navigator almost all of our tests are marked as "Ignored" with the reason "Project is not in build configuration"

However my projects are being built in this solution and I can run the tests manually but I have no way of running through all of the tests with a single click

chai expect does not check multiple classes using "to.have.class" api

The following test is to check whether an icon appears on a node or not. rootComponent.virtualComponentId =rootcomponent

   it("is sort icon visible on component tree", function() {
            var treeNode = $("<li>");
            var menuItem = {actionArgs: {id: "childComponentText"}};

            workspace.renderDstHintForMenuItemInTree(treeNode,menuItem);

            expect(treeNode).to.have.class("dst-hint-component-icon-tree  dst-hint-icon-tree-node dst-hints-" + rootComponent.virtualColumnId + "-last");
        });

Getting the following error.

AssertionError: expected <li><span title="View applied actions" class="dst-hint-component-icon-tree  dst-hint-icon-tree-node dst-hints-rootcomponent-last"></span></li> to have class 'dst-hint-component-icon-tree  dst-hint-icon-tree-node dst-hints-rootcomponent-last'

Is there any other way to test whether the particular class is applied or not ?

Kotlin test method says "not called" and then says that it is

Im trying to have a base class with a base traveler but when I try to test if the function form that base traveler was called it says that is not and then it says that there is!

open class BasePresenter<V : BaseView, T : BaseTraveler>() {
  var view: V? = null
  var traveler: T? = null
  var userRepository: UserRepository? = null
  val compositeSubscription = CompositeSubscription()

  @CallSuper
  open fun onCreate(view: V, traveler: T, userRepository: UserRepository) {
    this.view = view
    this.traveler = traveler
    this.userRepository = userRepository
  }

  //...
}

class LoginPresenter : BasePresenter<LoginView, LoginTraveler>() {
  override fun onCreate(view: LoginView, traveler: LoginTraveler, userRepository: UserRepository) {
    super.onCreate(view, traveler, userRepository)
    view.initViews()
  }

  fun onButtonLoginClick(username: String?, pwd: String?) {
    if (fieldsAreInvalid(username, pwd)) {
      return
    }

    view?.showProgressDialog()
    userRepository?.login(username!!, pwd!!)
        ?.compose(Transformations.applyIoSchedulers<Session>())
        ?.subscribe({
          view?.dismissLastProgressDialog()
          traveler?.startLoggedViewWithCleanStack()
        }, {
          view?.dismissLastProgressDialog()
          manageError(it, false)
        })
        ?.followLifeCycle(this)
  }
}

Test:

class LoginPresenterTest {
    @Mock lateinit var view: LoginView
    @Mock lateinit var traveler: LoginTraveler
    @Mock lateinit var userRepository: UserRepository
    lateinit var presenter: LoginPresenter

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        mockSchedulers()

        presenter = LoginPresenter()
        presenter.onCreate(view, traveler, userRepository)
        reset(view)
    }

    @Test
    fun test_onButtonLoginClick_ifSuccess_startMainView() {
        val session = MockSession.session()

        `when`(userRepository.login("clark", "123")).thenReturn(just(session))

        presenter.onButtonLoginClick("clark", "123")

        verify(view).showProgressDialog()
        verify(view).dismissLastProgressDialog()
        verify(traveler).startLoginViewWithCleanStack()
    }   
}

But I get Error:

Wanted but not invoked: traveler.startLoginViewWithCleanStack(); -> at LoginPresenterTest.test_onButtonLoginClick_ifSuccess_startMainView(LoginPresenterTest.kt:57)

However, there were other interactions with this mock: traveler.startLoggedViewWithCleanStack();

Why? Is it an inheritance problem?

C# Static Variable across tests in different test projects

I have 3 projects in my Visual Studio solution: 1 shared library project, 1 unit test project, and 1 coded UI test project (I had a hard time combining my unit tests and coded UI tests into 1 project - so we have 2). I have a static class with a static property in the shared library project called Globals.Status.

I have a unit test that changes this static Status variable. I have a coded UI test (in the coded UI project) that needs to read this updated Status variable. When I run these 2 tests consecutively, the variable is NULL when the coded UI test is invoked.

I have the coded UI test project referencing both the shared library project and the unit test project, but evidently this is not enough. What do I need to do to make this work?

Thanks for any insight!

Unit Testing angular $httpBackend service

I've got right now a project were we need to have the backend server mocked for the time being and we are using $httpBackend on the application .run feature. I need to unit test this service that contains the $httpBackend as we will be having a vast amount of mocked calls to the server we will be covering. So right now this is what I have. As a preface to my question the current setup works when I call 'mockDataService.getWorkflowTask' from a controller on a simple page.

My Server replacement service:

angular.module('app').run(function ($httpBackend, $resource, FakeBackendService) {
    // TODO: add all necessary http intercepts.  
    $httpBackend.whenGET('JSON file').respond(function (method, url, data) {
        var request = new XMLHttpRequest();
        request.open('GET', url, false);
        request.send(null);
        return [request.status, request.response, {}];
    });
    $httpBackend.whenGET(/.*/).respond(function (method, url, data) {

        return [200, FakeBackendService.getWorkflowTasks(), {}];
    });
});

Here is the service for FakeBackendService:

(function () {
    'use strict';

    var injectParams = [];

    function service(lodash) {
        var vm = this;

        var ret = {
            getWorkflowTasks: getWorkflowTasks
        };

        function getWorkflowTasks() {
            if (vm.workflowtasks.length < 1) {
                vm.workflowtasks = loadWorkflowTasks("Some JSON file");
            }
            return vm.workflowtasks;
        };

        function loadWorkflowTasks(file) {
            var workflowTasks = [];
            var request = new XMLHttpRequest();
            request.open("GET", file, false);
            request.send(null);

            if (request.status == 200) {
                workflowTasks = angular.fromJson(request.response);
            }
            return workflowTasks;
        };

        function init() {
            vm.workflowtasks = [];
        }

        init();

        return ret;
    }

    service.$inject = injectParams;
    angular.module('mock.FakeBackendService', []).service('FakeBackendService', service);
})();

So that is currently the backend server replacement mock. The following is my data handling service which contains the call to $http.get(blah blah blah).

(function () {
    'use strict';

    var injectParams = ['$http', '$q', 'mockConfigService', '$httpBackend'];

    function factory($http, $q, configService, $httpBackend) {
        var vm = this;

        var factory = {
            getWorkflowTask: getWorkflowTask
        };

        function getWorkflowTask(str) {
            return getResource(str);
        }

        function init() {
            // Get the URL we will be using to get data from
            vm.dataServiceURL = configService.getDataServiceURL();
        }

        function getResource(baseResource) {
            var resource = vm.dataServiceURL + baseResource;

            return $http.get(resource).then(function (response) {
                if (typeof response.data == 'object') {
                    // Got valid response
                    return $q.resolve(response.data);
                }
                else {
                    // Invalid response
                    return $q.reject(response.data);
                }
            }, function (response) {
                // Something went wrong
                return $q.reject(response.data);
            });
        }
        init();

        return factory;
    };

    factory.$inject = injectParams;

    angular.module('mock.dataService', []).factory('mockDataService', factory);
}());

Now for the Jasmine-Karma Unit test.

describe("HTTP Backend Mock testing", function () {

    beforeEach(angular.mock.module("app"));
    beforeEach(angular.mock.module("mock.FakeBackendService"));
    beforeEach(angular.mock.module("mock.configService"));
    beforeEach(angular.mock.module("mock.dataService"));

    it("Get the workflow task", angular.mock.inject(function (mockDataService) {
        var valid = "";

        var promise = mockDataService.getWorkflowTask('http://localhost/foo');

        promise.then(function (response) {
            valid = "Success";
        }, function (response) {
            valid = "Failure";
        });

        expect(valid).toBe("Success");
    }));
});

Now to the question. So, I'll start by saying I'm new to the AngularJS world and even more so to Jasmine. Anyways, when I debug the unit test I find that the promise's status is still 0 and I always get expected '' to be 'Success' telling my I never resolve (hopefully I'm using the right lingo) the promise from the $http service in mockDataService. I've tried playing around with it some and tried to see if anyone has done this kind of a thing before. I found plenty of examples where the $httpBackend is mocked in the test but none like what I'm attempting. Any ideas or suggestions would be great. Thanks.

How to set an Autowired field in an Aspect from junit test?

I have a Aspect that has an Autowired field config and in my unit test I would like to set a mock to config after defining mock behavior.

Aspect:

@Aspect
public class Aspect {

    @Autowired
    private Configuration config;

...

Unit Test:

@Autowired
private Configuration config;

@Before
public void setup() {
    when(config.getInt(TTL)).thenReturn(10000);
    // set confing to Aspect
}

I know spring has ReflectionTestUtils.setField for setting an autowired field, but I don't have a reference to the aspect object.

Google test: Can I query the name of the test fixture?

I want to use google test to write a class that derives from ::testing::Test and adds functionalities to it using mostly the constructor, or SetUp and TearDown(). Looks like SetUp/TearDown is the way to go so far. My question is:

Let's say we have a small test fixture like this:

TEST_F (PerformanceTest, Inputs)
{
   EXPECT_EQ (0.0, performSaxpy(10, 4.0F, 3.0F, 2.0F));
   EXPECT_EQ (0.0, performSaxpy(1, 5.0F, 4.0F, 3.0F));
   EXPECT_EQ (0.0, performSaxpy(10, 12.0F, 2.0F, 1.0F));
}

What I want to do is, when the SetUp() function is called, I want code inside that to query the name of the test fixture class (PerformanceTest), and the name of the test object (Inputs).

Why do I need to do this? Because I want to write the results of my test fixture to an xml file. For various reasons, I cannot use the default XML output format that google test already provides. However, in google test's default XML output, we get the names of the test fixture class and test object, so hopefully we can do it by custom... Is this possible?

Having trouble Jest testing ajax modules with axios

I have a module called ajax.js that exports a bunch of ajax functions for me. I'm trying to test the following function with Jest:

export const status = ({loginUrl='/', logoutUrl='/'}) => {
  return axios.get(`/auth?login=${loginUrl}&logout=${logoutUrl}`);
};

My test looks like this:

jest.unmock('../ajax');

import { status } from '../ajax';

describe('ajax', () => {
  let urls;

  beforeEach(() => {
    urls = {
      loginUrl: '/',
      logoutUrl: '/'
    };
  });

  it('calls status with a login and logout url', () => {
    const { loginUrl, logoutUrl } = urls;

    status(urls);
    expect(axios.get).toBeCalledWith(`/auth?login=${loginUrl}&logout=${logoutUrl}`);
  });
});

I keep getting a runtime error in my test:

runtime jest error

If I unmock axios, the error goes away, but that doesn't help me because I want axios to be mocked!

Also, the error appears to be happening because of this line:

import { status } from '../ajax';

Why is Jest struggling with axios so much. Why is simply importing my status function causing this error? Am I doing something wrong here?

How to mock DynamoDB batch save?

I wrote the dynamoDB code which stores list of items.

mapper.batchSave(trafficSensorReadings)

This will return.

List<FailedBatch>

I want to mock the mapper.batchSave and then return one failed job. How can I achieve it? I am using mockito and Junit.

I wrote something like this. But not useful.

        when(dynamoDBMapper.batchSave(eq(List.class))).thenReturn(mock(List.class));

Google Unit Test to check Table Printing

Is it possible to use google unit test to test table printing with c++?

Can that be done with other unit test framework?

So far, in A quick introduction to the Google C++ Testing Framework I only see test of values. This question at SO talks about using google mock to test arrays.

Resharper unit test sessions changing test results to unknown after build

I am running a suite of NUnit tests using the Unit Test Explorer/Sessions window in Resharper Ultimate 9.2 and Visual Studio Enterprise 2015. I start a new test session from the unit test explorer every night with the tests that I want to run and run all of them from within the unit test sessions window after renaming the new session to include the current date. Most of the time the results are remembered with no trouble and I can work through the results and debug the ones which failed, but sometimes after building all of my test results in all sessions will get marked with "unknown" result status.

This doesn't always happen and it seems to happen more often if I merge lots of code changes in from a different TFS branch.

Is there any way to force resharper not to mark the tests as unknown and retain all the results that I had? I know that I can export the results to XML (and do now, for this very reason) but it's harder to read and navigate the results in an XML file than the Resharper unit test sessions window, so I'd lilke to do that if possible.

How to use a bootstrap file with mocha?

I wish to boostrap mocha.

npm cmd:

 "tests": "mocha assets/test --compilers js:babel-core/register --require assets/test/bootstrap.js",

bootstrap.js

import chai from 'chai'
import chaiEnzyme from 'chai-enzyme'
import {shallow} from 'enzyme'
import React from 'react'


chai.use(chaiEnzyme())
const expect = chai.expect

example file

import Navigation from './../jsx/Navigation.jsx'

describe('<Navigation />', () => {
    const wrapper = shallow(<Navigation />)
    it('render el nav', () => {
        expect(wrapper).to.have.descendants('nav')
    })
})

Gives error:

ReferenceError: shallow is not defined

Not sure why EVERYTHING has to be so difficult with js. How to I do this simplistic thing?

How to throw a parseException in a switch statement?

To increase my projects code coverage, I need to reach the branch ParseException in this method:

public String filterMessage(String actionIn, String messageIn) {
        String message = null;
        try{
            switch (actionIn) {
            //..
            default:
                message = messageIn;
                break;
            }
        }catch (ParseException e) {
            System.out.println("Encountered parse exception");
            e.printStackTrace();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
        return message;
    }

Instincts are that we must put a String that is "illegal", that can't be parsed because it isn't actually a String, but how do you place something like that without causing a compile error (like putting an int to cause faulse parsing). Any ideas how to test this catch "branch"?

Howto create and run a list of type TestClass(with different ctor-props) and run it

I have a TestClass called ActivityTestsFor27Jun and ActivityTestsFor13Sep. These classes contain 6 TestMethods. I have a base class which set-up some things. They share a ton of the same vars. The only different vars are month, day of type int and sunset of type DateTime.

What I want to build is a TestClass called ActivityTest which takes 3 params in his constructor: month, day, sunset

Now I want to make some kind of a start class where I can do this

List<ActivityTest> activityTestList = new List<ActivityTest>();
activityList.add(new ActivityTest(6, 27, sunsetVal1));//27 jun
activityList.add(new ActivityTest(9, 13, sunsetVal2));//13 sep
activityList.add(new ActivityTest(x3, y3, sunsetVal3));// and so on..

And now something like Run(activityTestList);

A link to point me the way is also appreciated!

How do I fake a "click to continue" in the middle of a save method for testing?

The below code is in the body of the save method and the clickHandler for the toaster finishes the save process. So, what I need to do is fake a click during my save method. I know how to retrieve an element and fire a click, but I don't know how to do it correctly for this particular test.

return promise.then(() => {

    // warn user
    if (!mustPromptUser) {
        ctrl.toasterService.warning({
            body: "A message",
            timeout: 0,
            showCloseButton: true,
            clickHandler: onSaveFunc, <--- must assert this happened
            bodyOutputType: "trustedHtml"
        });
    } else {
        onSaveFunc();
    }
}).catch(() => {
    // some code
});

Here is the test:

    it("Can I get this damned test working", () => {
        var controller = initializeController(model) as MyController;
        controller.form = {
            $pristine: true,
            $setPristine: null
        } as ng.IFormController;
        spyOn(controller, "onSave");
        spyOn(controller.form, "$setPristine");
        spyOn(service, "create");
        controller.save();
        $timeout.flush();

        expect(service.create).toHaveBeenCalled();
        expect(toaster.warning).toHaveBeenCalled();
        // This is the assertion that's failing because the user has to click to call this method in the toaster clickHandler. 
        expect(controller.onSave).toHaveBeenCalled();
        expect(controller.form.$pristine).toBeTruthy();

    });

Analyzing Code Coverage for one TestFixure

I have one TestFixture for menu and one for products.

enter image description here

I now want to know how much code that one fixture covers.

It does not seem that I can click Analyze Code Coverage -> Selected Tests on a testfixture.

When I use the test explorer it organizes the test in Passed/Not Passed/Not Run. There does not seem to be a grouping by testfixture.

So is there a way I can see code coverage for just one testfixture without having to manually go through the entire list and pick out each test?

store results of automatic tests and show results in a web UI

I'm looking for a piece (or a set) of software that allows to store the outcome (ok/failed) of an automatic test and additional information (the test protocol to see the exact reason for a failure and the device state at the end of a test run as a compressed archive). The results should be accessible via a web UI.

I don't need fancy pie charts or colored graphs. A simple table is enough. However, the user should be able to filter for specific test runs and/or specific tests. The test runs should have a sane name (like the version of the software that was tested, not just some number).

Currently the build system includes unit tests based on cmake/ctest whose results should be included. Furthermore, integration testing will be done in the future, where the actual tests will run on embedded hardware controlled via network by a shell script or similar. The format of the test results is therefore flexible and could be something like subunit or TAP, if that helps.

I have played around with Jenkins, which is said to be great for automatic tests, but the plugins I tried to make that work don't seem to interact well. To be specific: the test results analyzer plugin doesn't show tests imported with the TAP plugin, and the names of the test runs are just a meaningless build number, although I used the Job Name Setter plugin to set a sensible job name. The filtering options are limited, too.

My somewhat uneducated guess is that I'll stumple about similar issues if I try other random tools of the same class like Jenkins.

Is anyone aware of a solution for my described testing scenario? Lightweight/open source software is preferred.

FileLoadException on project references when running tests

I have some test projects that have reference to dlls that are constantly being uptade by a server who build them. So far so good. But sometimes when I run the tests, the test Project tries to load the previous version of referenced dll.

Ex: The referenced dll is in 6.5.0.381 version, but my test Project looks for the 6.5.0.380 version, raising the following exception:

System.IO.FileLoadException : Could not load file or assembly “myassembly, Version=6.5.0.380”

Checking the properties of the reference, the build of the reference is in the correct version (6.5.0.381 - the new version).

Is there any other location where the Project keeps the version of referenced dlls?

Testing that a Logback Log statment was called using Junit?

Below is a method that I am attempting to write Junit test for:

Method I wish to test:

public void showOutputOfIdentifications(int age) {

    if(age>25){

        LOGGER.info("Over 25");

    }else{

        LOGGER.info("25 or Under");

    }
 }

How can I test to verify that the correct Logback Log statement has been called?

In my tests I have tried to mock the logger and verify that it was called, however this has not worked?

Current Test Attempt:

 @Test
    public void testShowOutputOfIdentifications() throws ParseException{

    int age = 10;

    Logger LOGGER_mock = mock(Logger.class);

    //call method under test
    showOutputOfIdentifications(age);

    verify(LOGGER_mock).info("25 or under");


}

Current failing test output:

Wanted but not invoked:
logger.info(
    "25 or under "
);

Actually, there were zero interactions with this mock.

ci_phpunit_test: Help needed about test double with queries

i'm learning about unit testing with CodeIgniter and i would to ask some questions about testing queries with Mocks class.

I tried to implement the following class News_model with the method get_news_all() that returns all news data from table 'news' and get_news returns only title and text fields from the same.

class News_model extends CI_Model
{
public function __construct(){
    $this->load->database();
}

public function get_news_all()
{
    $query=$this->db->get('news');
    $result=$query->result_array();
    return $result;
}

public function get_news()
{
    $this->db->select('title, text');
    $this->db->from('news');
    $query=$this->db->get();
    $result=$query->result_array();
    return $result;
}

After i tried to build a News_model_with_mocks_test for testing method get_news_all() and in this case test runs fine:

class News_model_with_mocks_test extends TestCase
{
public function setUp()
{
    $this->resetInstance();
    $loader=$this->getMockBuilder('CI_Loader')->setMethods(['database'])->getMock();
    $loader->method('database')->willReturn($loader);
    $this->CI->load=$loader;
    if(!class_exists('CI_DB', false))
    {
        eval('class CI_DB extends CI_DB_query_builder {}');
    }
    $this->obj=new News_model();
}

public function test_1()
{
    $result_array = [
            [
                    "id" => "1",
                    "title" => "News",
                    "slug" => "news",
                    "text" => "News",
            ],
            [
                    "id" => "2",
                    "title" => "News2",
                    "slug" => "news2",
                    "text" => "News2",
            ],
    ];
    $db_result=$this->getMockBuilder('CI_DB_result')->disableOriginalConstructor()->getMock();
    $db_result->method('result_array')->willReturn($result_array);
    $db = $this->getMockBuilder('CI_DB')->disableOriginalConstructor()->getMock();
    $db->expects($this->once())->method('get')->with('news')->willReturn($db_result);
    $this->obj->db=$db;
    $result=$this->obj->get_news_all();
    $this->assertEquals($result_array,$result);
}

}

But i don't know how to do tests for the method get_news(), i tried something as this:

public function test_1()
{
    $result_array2 = [
            [
                    "title" => "News",
                    "text" => "News",
            ],
            [
                    "title" => "News2",
                    "text" => "News2",
            ],
    ];
    $db_result=$this->getMockBuilder('CI_DB_result')->disableOriginalConstructor()->getMock();
    $db_result->method('result_array')->willReturn($result_array2);
    $db = $this->getMockBuilder('CI_DB')->disableOriginalConstructor()->getMock();
    $db->expects($this->once())->method('query')->with('select title,text from news')->willReturn($db_result);
    $this->obj->db=$db;
    $result=$this->obj->get_news();
    $this->assertEquals($result_array2,$result);
}

phpunit thows the following exception:

PHP Fatal error:  Call to a member function result_array() on a non-   object in /opt/lampp/htdocs/codeigniter/application/models/Users_model.php on line 21

I don't know how to test double with select queries! Thank you in advance for your answers.

Ember unit test computed property with then

I have the following model: partner.js

  invoices: hasMany('invoice'),
  resolvedInvoices: computed('invoices', {
    get(){
      let value = null;
      let _this = this;
      this.get('invoices').then(invoices=>{
        _this.set('resolvedInvoices', invoices);
      });
      return value;
    },
    set(key,value) {
      return value;
    }
  }),

I try to unit test it: partner-test.js

test('test', function(assert) {

  let partner = this.subject();
  let store = this.store();
  // set a relationship
  run(() => {
    let invoice = store.createRecord('invoice', {

    });

    partner.get('invoices').pushObject(invoice);
    console.log(partner.get('resolvedInvoices'));
  });
  assert.ok(true);
});

But console.log always shows null. Is it possible to wait till the computed property's then runs, and the new value sets?

Spying on a service call in controller test and returning different values

I'm spying on a service function call in a test spec for a controller, and am returning the result of a promise.

In my test spec I am calling the service function a couple of times and am wanting to resolve with different response data each time.

I currently have this:

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

beforeEach(inject(function(_MyService_, _$rootScope_, _$controller_, _$q_) {
    myService = _MyService_;
    $rootScope = _$rootScope_;
    $q = _$q_;
    $controller = _$controller_;
    $scope = $rootScope.$new();

    getListPromise = $q.defer();
    spyOn(myService, 'getList').and.returnValue(getListPromise.promise);
}));

describe('When a current financial period with a firstOccurrence greater than one is supplied to the controller', function() {
    beforeEach(function() {
        ctrl = $controller('MyController', {
        });
        getListPromise.resolve({test: 'hello'});
        $scope.$apply();
    });

    describe('Controller activation', function() {
        it('should call myService.getList', function() {
            expect(myService.getList).toHaveBeenCalled();
        });
    });

    describe('getListByQuery', function(){
        beforeEach(function(){
            ctrl.getListByQuery();
            getListPromise.resolve({foo: 'bar'});
            $scope.$apply();
        });
        it('should do something here...', function() {
            expect(...)
        });
    });
});

On initialisation the controller calls my service function, it also calls it from a getListByQuery function in the controller.

I have added a console log to the call to myService.getList in the controller, to log out the value of the result returned in a promise:

myService.getList().then(function(result){
    vm.listData = result;
    console.log(result);
});

So I would expect to see logged out in my test console (using Karma\Jasmine) {test: 'hello'} followed by {foo: 'bar'}

But I see {test: 'hello'} logged out twice.

I'm unsure why this is happening, can any one offer any explanations?

Thanks

Using Different Test Runners For Different Tests

I am using Dagger 2 and trying to provide different dependencies at test time.

I can provide different dependencies for the tests but unfortunately, these then apply to all tests in the androidTest directory.

I do this by specifying a TestAppComponent which uses a TestAppModule. In my TestApplication, which extends my AndroidApplication, I supply the TestAppComponent rather than the real AppComponent. Then I have TestRunner that extends the newApplication method like so:

@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return super.newApplication(cl, TestApplication.class.getName(), context);
}

Then to use this runner I replace the current runner with the following:

testInstrumentationRunner "com.company.myapp.TestRunner"

My Question

How do I use a different component/application/test runner for different tests rather than use the same for each one? I may want to mock a dependency in one test but not in another?

Symfony, Call service in PHP Unit

I have a unit test, where I need to call a service.

I did it that way:

<?php
namespace FM\PriceBundle\Tests\Service;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class PriceServiceTest extends KernelTestCase
{
    private $container;

    public function testFiulPrice()
    {
        self::bootKernel();
        $this->container = self::$kernel->getContainer();

        $productId = 1;
        $id = 1;
        $what = ['postal', 'departement', 'region', 'country', 'insee'];
        $date = new \DateTime('2016-06-23');

        $price = $this->container->get('fm.price.get')->fiulPrice($productId, $id, $what[0], $date);

        $this->assertNotEmpty($price);
    }
}

But I have this error:

There was 1 error:

1) FM\PriceBundle\Tests\Service\PriceServiceTest::testFiulPrice Predis\Connection\ConnectionException: Connection refused [tcp://localhost:6379]

Flurl & HttpTest: Unit tests fail when Run All, but pass when run individually

I have a really weird pair of test utilizing Flurl and xUnit that, when Run All in VS Test Explorer, will fail, but if run individually, will pass. I cannot for the life of me see anywhere where the 2 are even related to each other, but they do.

I have extracted them out of my project into a new project and the problem persists. I bundled them into a 7z for anyone interested in loading it to VS, but the full code follows.

Project.Commons

GetApi1:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;

namespace Project.Commons
{
    public class GetApi1
    {

        public async Task<string> ExecuteAsync(string token)
        {
            string apikeyKeyname = "token";

            dynamic response = await "http://www.api.com"
                .SetQueryParams(new { token = token })
                .GetJsonAsync();

            string receivedApiKey = ((IDictionary<string, object>)response)[apikeyKeyname].ToString();

            return receivedApiKey;
        }
    }
}

GetApi2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;

namespace Project.Commons
{
    public class GetApi2
    {
        public async Task<IList<string>> ExecuteAsync()
        {
            var responses = await "http://www.api.com"
                .GetJsonAsync<List<string>>();

            var result = new List<string>();

            foreach (var response in responses)
            {
                result.Add("refined stuff");
            }

            return result;
        }
    }
}

Project.Tests

UnitTest1:

using Project.Commons;

namespace Project.Tests
{
    public class UnitTest1
    {
        private ITestOutputHelper output;
        public UnitTest1(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public async Task ShouldBeAbleToGetApiKeyFromToken()
        {
            // Arrange
            using (var httpTest = new HttpTest())
            {
                var jsonResponse = new { token = "abcdef" };
                string expectedApiKey = "abcdef";
                httpTest.RespondWithJson(jsonResponse);
                var api = new GetApi1();

                // Act
                var receivedApiKey = await api.ExecuteAsync("mockToken");
                output.WriteLine("Received apikey = " + receivedApiKey);

                // Assert
                Assert.Equal(expectedApiKey, receivedApiKey);
            }
        }
    }
}

UnitTest2

using Flurl.Http.Testing;
using Project.Commons;
using Xunit;
using Xunit.Abstractions;

namespace Project.Tests
{
    public class UnitTest2
    {


        #region Mock API JSON Response
        private IList<string> mockResponse = new List<string>()
        {
            "raw stuff", "raw stuff", "raw stuff"
        };
        #endregion

        #region Expected Result
        private IList<string> expectedResult = new List<string>()
        {
            "refined stuff", "refined stuff", "refined stuff"
        };
        #endregion

        [Fact]
        public async Task CanGetProjectsByWeek()
        {
            // Arrange
            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWithJson(mockResponse);

                // Act
                var api = new GetApi2();
                var actualResult = await api.ExecuteAsync();

                // Assert
                Assert.Equal(expectedResult,actualResult);
            }
        }
    }
}

Different build configurations for test schemes

I have a unit test and a performance test scheme. In the test configuration for the unit test scheme, I selected debug build, and for the performance test scheme I selected release build. If I run each scheme individually, I get a debug build and a release build respectively.

If I create another scheme that runs both of these schemes, then that new scheme will have its own build configuration. If I set a build configuration of debug for this new scheme, then I will get a debug build for my performance tests as well.

Is there a way to run the unit tests in a debug build and performance tests in a release build without manually selecting and running each individual scheme?

Bouncy Castle Issue when Unit Testing Android

We are using BouncyCastle library in our android application. It is injected in Application singleton in static form:

static {
        java.security.Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}

But when I run local unit tests, the system throws me NoSuchProvider Exceptions at every place it was using Bouncy Castle. So, the question is how to inject Bouncy Castle Providers into android local unit tests?

mercredi 29 juin 2016

Testing private methods with JUnit [duplicate]

This question already has an answer here:

I'm getting into using Junit to test individual methods that have been implemented in a class. But it cannot test private methods. What is the best way to proceed? It seems like a bad idea to convert all methods to public and then back to private because the whole point of JUnit is to remove the chance of human error when manually testing.

Unit Test using TestNG + Spring mybatis

I have webapp using integrated spring and mybatis . @Transaction works fine in spring mvc , but not in my unit test .

code is worth than thousand words ,

application-test.xml

<context:annotation-config/>



<context:component-scan base-package="com.isildur"/>

<!-- middleware datasource  -->
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/istaritest"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>




<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--<property name="configLocation" value="SqlMapConfig.xml" />-->
    <!--<property name="typeAliasesPackage" value="com.isildur.security.entity"/>-->
    <property name="mapperLocations" value="classpath:/mapper/**/*.xml"/>
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.isildur"/>
</bean>


<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource"/>
</bean>

unit test

@ContextConfiguration(locations = {"classpath:application-test.xml"})

public class CustomerRepoTest extends AbstractTestNGSpringContextTests {
@Autowired
CustomerRepo customerRepoImpl;

@Transactional(rollbackFor = Exception.class)
public void testCreateCustomer() throws Exception {

        Customer cust = new Customer();
        cust.setAccountCode("2");
        cust.setMobileNumber("3");
        cust.setEmailAddress("ad@gmail.com");

        customerRepoImpl.save(cust);




        Customer cust2 = new Customer();
        cust2.setAccountCode("5");
        cust2.setMobileNumber("3");
        cust2.setEmailAddress("3@gmal.com");

        customerRepoImpl.save(cust2);
        throw new Exception("canceled");


    }
}

output in console

 JDBC Connection [com.mysql.jdbc.JDBC4Connection@44536de4] will not be managed by Spring

it should be canceled because an exception . but it still insert into db .

Did i miss the configuration ?

any ideas are welcome .

thanks .

Mockito MVC - how to pass value for @RequestParam binding a string array

I'd like to write a unit test using Mockito.

The method to be tested is written by Spring MVC as follows:

@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(String appName,
        @RequestParam(value = "platforms[]") String[] platforms,
        HttpServletRequest request) {}

I tried several ways to mock request value platforms which is binding a string array like 'string[]'.

But, it seems it is still not working: the platforms value is null.

Here are the ways I tried:

Way#1

final String[] platforms = { "Android", "iOS" };
request.setAttribute("platforms", platforms);
request.setAttribute("platforms[]", platforms);

Way#2

mockMvc.perform(MockMvcRequestBuilders.post("/application/save")
            .session(session).requestAttr("platforms[]", platforms)
            .requestAttr("platforms", platforms)
            .param("appName", "Just for test"));

Note: request is a mock object (MockHttpServletRequest)

Hope you can give me some idea to solve this problem. Thanks.

Visual Studios Unit Tests passing locally, "Not Executed" on build server

I am currently running into an issue with Unit tests passing locally, but getting reported "failed" test cases on our build servers. Locally, I am running win7 VS2013 test agent and the build servers are running win8 VS2013 test agent.

Firstly, all our tests are passing on our local machines, so we are having trouble reproducing the problems on the build server. Secondly, on the build servers, the tests are reporting that they aren't being executed, but based on the console output as well as some coverage information reported, we can see that the tests are actually running (which is a mystery to us).

We have attempted the tests locally and all our local machines will pass, but all our server machines will not pass certain tests. Also we have attempted to rollback to a previous state on the build server that was passing, but even that has not worked. We have already attempted a clean build/rebooting of the build machines, but nothing has helped so far as the tests are still reported as "not executed" (console outputs suggest that it is running since our debugging information is being printed). The tests are running in parallel on the build server, but that shouldn't be an issue as it was running fine before.

anyone running into this issue or have a solution or a suggestion on where to look?

-L

sqllite as inmmeory db for mssql

My setup is similar to this for testing dapper calls for mssql using in memory sqllite. http://ift.tt/294FQhV

Using this lib http://ift.tt/1dUGmJ2

I'm using dapper with ad hoc sql for my DAL and wanted to test data access layer without dependency on sql server. I used sqllite inmmeory db. Problem is sql sytanx are different between mssql and sqllite. For example I have a query that returns paged results using offset and fetch next , but sqllite only supports limit and offset. What if any suggestions you have for me to do my in memory unit test? I didn't go ef route with mocked db context as dapper is more performant and didn't want to use sproc as I wanted to test my sql as well. I'm not looking to mock my db calls.

Can I use Xcode Test Navigator for EarlGrey tests?

Like the following:

Image: http://ift.tt/293Cgnw

Xcode Test Navigator

Mock ApplicationUserManager for Unit Testing MVC controllers

I would like to know if someone can help me with this.

I am writing unit tests for a specific controller. That controller inherits from a BaseController and that BaseController has this property:

private ApplicationUserManager userManager;
public ApplicationUserManager UserManager 
{ 
    get { return this.userManager ??  this.Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); } 
    set { this.userManager = value; } 
}

The ctor for ApplicationUserManager is:

public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService)
        : base(store)
    {
        this.EmailService = emailService;

        var dataProtectionProvider = Startup.DataProtectionProvider;
        this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
    }

This is what I am doing to mock the ApplicatonUserManager class:

var store = new Mock<IUserStore<ApplicationUser>>();
var emailService = new Mock<IIdentityMessageService>();
var applicationUserManager = new Mock<ApplicationUserManager>(store.Object, emailService.Object);
this.targetController.UserManager = applicationUserManager.Object;
var dataprotectionprovided = new Mock<IDataProtectionProvider>();
applicationUserManager.Setup(r => r.UserTokenProvider).Returns(new DataProtectorTokenProvider<ApplicationUser, string>(dataprotectionprovided.Object.Create("ASP.NET Identity")));
this.targetController.UserManager = applicationUserManager.Object;

I have tried to mock this but because this is not virtual property (UserTokenProvider) it does not allow me and I get this exception:

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: r => r.UserTokenProvider

Can anyone help me with this problem? I just want to mock this in order to test the controller that inherits from a BaseController that has that property..

Thanks

How to override an implicit conversion in my scala test?

I am working on a scala test that tests the code which uses implicit conversion methods. I don't want to use those implicit conversions and would like to mock/override them in the test. Is it possible to do that ?

How to Mock TCPClient by implementing the interface

I am new to computer science and have few knowledge in network. I got a task in my internship.It is to mock a TCPClient by implement Interface. The idea is that since we don't need to connect to the real server, we just need a mock TCPClient to receive data, save it and send it out. From what I understand, is it just to mock the sendmessage function in TCPClient??

public interface ITCPClient
{
    /// <summary>
    /// Event handler when TCP client is connected 
    /// </summary>
    event ConnectionEventHandler Connected;

    /// <summary>
    /// Event handler for TCP Client on receiving data
    /// </summary>
    event DataReceivedEventHandler DataReceived;

    /// <summary>
    /// Event handler when TCP client is disconnect
    /// </summary>
    event ConnectionEventHandler Disconnected;

    /// <summary>
    /// Reports error when an error occurs
    /// </summary>
    event ErrorEventHandler OnError;

    /// <summary>
    /// Set whether to use HostByteOrder or NetworkByteorder with the socket - gateway expects network byte order
    /// </summary>
    bool ByteOrder { get; set; }

    /// <summary>
    /// Returns true if the client is running and connected to the server
    /// </summary>
    bool IsRunning { get; }

    /// <summary>
    /// Add the message to the sendqueue. The message will be processed by the ProcessMessage function waiting for the message.
    /// </summary>
    /// <param name="Message"></param>
    void SendMessage(string Message);

    /// <summary>
    /// Add the message to the sendqueue. The message willbe processed by the ProcessMessage function waiting for the message.
    /// </summary>
    /// <param name="Message"></param>
    void SendMessageHiPriority(string Message);

    /// <summary>
    /// Starts the client and spawn the thread for processing the message
    /// </summary>
    void Start();

    /// <summary>
    /// Disconnects and stops listening for messages 
    /// </summary>
    void StopProcessing();

}

public class MockTCPClient : ITCPClient
{
    #region Private Fields

    private string msg;

    #endregion Private Fields


    #region Constructor

    public MockTCPClient()
    {
        //nothing 
    }


    #endregion Constructor

    #region event

    public event ConnectionEventHandler Connected;
    public event ConnectionEventHandler Disconnected;
    public event ErrorEventHandler OnError;
    public event DataReceivedEventHandler DataReceived;

    #endregion event 

    #region property
    //question 
    public string ReceivedMessage
    {
        get
        {
            return msg;
        }

        set
        {
            msg = value;
        }

    }

    #endregion property

    //question??
    private void OnDataReceived(object sender, string e)
    {
        DataReceivedEventHandler dataReceived = DataReceived;
        if (dataReceived != null)
            dataReceived(this, e);
    }


    #region ITCPClient Members
    #region properties

    public bool ByteOrder { get; set; }


    public bool IsRunning { get; }

    #endregion properties

    public void SendMessage(string Message)
    {
        msg = Message;
    }

    public void SendMessageHiPriority(string Message)
    {    
    }

    public void Start()
    {
    }


    public void StopProcessing()
    {
    }


    #endregion ITCPClient Members

}

HttpEntity< String > request = new HttpEntity< String >( ); How do I mock this in java

I am trying to mock generics I am able to mock some of the generic expression but I have no idea how to mock generic initialization

Karma test throws a Provider not found error on a service

I am trying to create a simple service and test it in jasmine-karma environment.

I have used Angular 1.5.5

For some reason I keep getting a error

Chrome 46.0.2490 (Windows 7 0.0.0) reddit api service should do something FAILED
    Error: [$injector:unpr] Unknown provider: redditServiceProvider <- redditService
    http://ift.tt/299URmO
        at c:/client/www/vendor/angular/angular.js:68:12
        at c:/client/www/vendor/angular/angular.js:4502:19
        at Object.getService [as get] (c:/client/www/vendor/angular/angular.js:4655:39)
        at c:/client/www/vendor/angular/angular.js:4507:45
        at getService (c:/client/www/vendor/angular/angular.js:4655:39)
        at injectionArgs (c:/client/www/vendor/angular/angular.js:4679:58)
        at Object.invoke (c:/client/www/vendor/angular/angular.js:4701:18)
        at Object.workFn (c:/client/node_modules/angular-mocks/angular-mocks.js:3078:20)
    Error: Declaration Location
        at window.inject.angular.mock.inject (c:/client/node_modules/angular-mocks/angular-mocks.js:3040:25)
        at Suite.<anonymous> (c:/client/www/app/mine/myspec.spec.js:12:16)
        at c:/client/www/app/mine/myspec.spec.js:7:3
        at c:/client/www/app/mine/myspec.spec.js:52:3
    TypeError: Cannot read property 'whenGET' of undefined
        at Object.<anonymous> (c:/client/www/app/mine/myspec.spec.js:18:18)
Chrome 46.0.2490 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.049 secs)
Chrome 46.0.2490 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.048 secs / 0.049 secs)
29 06 2016 13:03:43.349:DEBUG [karma]: Run complete, exiting.
29 06 2016 13:03:43.349:DEBUG [launcher]: Disconnecting all browsers
29 06 2016 13:03:43.650:DEBUG [launcher]: Process Chrome exited with code 0
29 06 2016 13:03:43.652:DEBUG [temp-dir]: Cleaning temp dir C:\Users\mine\AppData\Local\Temp\karma-78283773
29 06 2016 13:03:44.892:DEBUG [launcher]: Finished all browsers
[13:03:44] 'karma' errored after 15 s
[13:03:44] Error: 1

My service file is:

 angular.module("reddit",[]).service("userService",
  function($http) {
    return {
      getSubredditsSubmittedToBy: function(user) {
        return $http.get("http://ift.tt/2951UdN" + user + "/submitted.json").then(function(response) {
          var posts, subreddits;

          posts = response.data.data.children;

          // transform data to be only subreddit strings
          subreddits = posts.map(function(post) {
            return post.data.subreddit;
          });

          // de-dupe
          subreddits = subreddits.filter(function(element, position) {
            return subreddits.indexOf(element) === position;
          });

          return subreddits;
        });
      }
    };
  });

My test looks like this:

(function(){
  "use strict";

  describe("reddit api service", function () {
    var redditService, httpBackend;

    beforeEach(module("reddit"));

    beforeEach(inject(function (_redditService_, $httpBackend) {
      redditService = _redditService_;
      httpBackend = $httpBackend;
    }));

    it("should do something", function () {
      httpBackend.whenGET("http://ift.tt/299UZCX").respond({
        data: {
          children: [
            {
              data: {
                subreddit: "golang"
              }
            },
            {
              data: {
                subreddit: "javascript"
              }
            },
            {
              data: {
                subreddit: "golang"
              }
            },
            {
              data: {
                subreddit: "javascript"
              }
            }
          ]
        }
      });
      redditService.getSubredditsSubmittedToBy("yoitsnate").then(function(subreddits) {
        expect(subreddits).toEqual(["golang", "javascript"]);
      });
      httpBackend.flush();
    });

  });

})();

I have followed this tutorial(http://ift.tt/1qt1OOe) to create this service(rather I copied it) I assume that it does work and there is some other issue going on. I got some one elses working code and any service tested works fine. Please let me know where I am wrong. Thanks!

How to create unit tests in C with framework

I need to create simple unit tests in c where the testing will involve reading a file and determining whether correct output/results are produced. I'm assuming I'd need a unit testing framework for this.. could you recommend a suitable one and also guide me through its setup? i.e. linking it up to my program (ensuring I use the correct path when including it to my c program). Up until now I've tried CUnit, Googletest and Check but I just can't seem to get them to 'link' up with my program. Every time I try and install the packages I get errors on the command line. I just need some guidance on how to successfully install the package and also get my program to be able to use it.

Any help would be greatly appreciated - I'm completely stuck!

Automate Unit Testing in Jenkins

I have a pl/sql project in SQL Developer. I use SQL Developer unit test for performing unit tests on the PL/SQL project.

I am trying to implement continuous integration for this project by using Jenkins.

I want to know how can I configure Jenkins to run these unit tests of SQL Developer ?

Any information or suggestions would be very helpful.

Thanks

EventHub PartitionContext Class Design

I am trying to test my implementation of the IEventProcessor. However, I am having a hard time, because it is impossible to actually mock the PartitionContext class (http://ift.tt/295i7Dn).

For example, I can not verify if the CheckpointAsync() method has been called correctly, because the ICheckpointer interface is internal and the actual method is not virtual. Furthermore, I can not inject my own ICheckpointManager instance, because the constructor which allows this, is internal.

What is the design decisions in making everything internal, which would allow me to mock this class?

Either this is really bad design or I am missing something.

Add items to collection in fake object

I have started my unit testing with Microsoft fakes , facing some difficulties while creating Shim objects. In my actual object I can easily add an item to my collection , not sure how to add fake object to a fake collection

Actual Implementation

var checklist2 = new CampusDoor.Fulfillment.Checklist.Messages.Entities.ApplicationChecklist();
                checklist2.ChecklistItems = new CampusDoor.Fulfillment.Checklist.Messages.Collections.ApplicationChecklistCollection();
                checklist2.ChecklistItems.Add(new ChecklistItem() { ChecklistItemCode = CampusDoor.Fulfillment.Checklist.Messages.Entities.Enumerators.ChecklistItemCode.BorrowerPermissionToPullCredit, IsChecked = true });
                checklist2.ChecklistItems.Add(new ChecklistItem() { ChecklistItemCode = CampusDoor.Fulfillment.Checklist.Messages.Entities.Enumerators.ChecklistItemCode.CosignerPermissionToPullCredit, IsChecked = true });      

Fake object creation so far

var checklist = new CampusDoor.Fulfillment.Checklist.Messages.Entities.Fakes.ShimApplicationChecklist()
                {
                    ChecklistItemsGet =()=> new CampusDoor.Fulfillment.Checklist.Messages.Collections.Fakes.ShimApplicationChecklistCollection()
                    {

                    },

                };

I need to pass IsChecked = true of ChecklistItem and add it to ApplicationChecklistCollection ,

Visual Studio Unit Testing Framework tests failing

I have a small application and 2 unit tests look for exceptions and so I have the decorator [ExpectedException(typeof(ArgumentException))] on them. When I run the tests individually everything is fine. If I run all, the 2 with the exception decorators will fail and the others succeed. If I run a group of tests where this 1 test that has the ExpectedException on it, that test will fail. The tests are really small and below are the 2 that have the exception decorator.

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void WrongArgCountExceptionThrown()
        {
            List<string> args = new List<string>
            {
                "-t",
                "table_name",
                "-d",
                "2016-06-30"
            };

            Program prg = new Program();
            prg.Run(args.ToArray(), new Data(logRepo.Object, queueRepo.Object));
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void WrongArgFormatExceptionThrown()
        {
            List<string> args = new List<string>
            {
                "t",
                "table_name",
                "-d",
                "2016-06-30",
                "-i",
                "1"
            };

            Program prg = new Program();
            prg.Run(args.ToArray(), new Data(logRepo.Object, queueRepo.Object));
        }

Moq with delegate in Returns always returns null

I am trying to make a Mock object for a class, so that the Mock object has access to all of the same methods as the original class, except for the one method I want to perform differently. However, my Mock object has no methods when I view it in Debug mode, and all of the calls I don't want to alter (for testing purposes) return null. Here is the way I am presently doing this:

var originalClass = ContainingClass.OtherContainingClass.ClassIWantToMock;
var originalClassMock = new Mock<IClassToMock> {CallBase = true};

originalClassMock.Setup(c => c.MethodToMock(It.IsAny<paramType>()))
    .Returns<TReturn>(originalClass.MethodToMock);

I get the same result whether I only mock the method I want to change, as well as when I mock every method in the class. I suspect this is because IClassToMock is an interface, even though I am feeding in methods from an object that implements that interface. This is probably why CallBase does not make a difference--I get the same result regardless of whether CallBase is set. Is there a way to mock an interface by setting up methods that run delegates from a class implementing that interface?

Thanks!

Stubb interface pointer parameters in Golang

Say that I have a Storage which maps client id's to net.Conns (interface). For the sake of simplicity, it's just hides a map inside it and gets map key as a parameter.

I want to eliminate the need for value copying, and I come from the land of Java, so it seems logical that the map should map id's to net.Conn pointers.

type Storage struct {
     conns map[int]*net.Conn
}

func (s *Storage) Add(id int, conn *net.Conn){
   s.conns[id] = conn
}

... methods for initialising new storage, getting, deleting, 
maybe giving list of user id's etc.

Now I want to write automatic tests for the code, but without actual Conns, so I write my own StubbConn and Stubb all the net.Conn -interface methods.

type StubConn struct{}

func (s *StubConn) Read(b []byte) (n int, err error)   { return 0, nil }
func (s *StubConn) Write(b []byte) (n int, err error)  { return 0, nil }
etc..

And then I try to use this StubbConn in testing...

func TestAddOneClient(t *testing.T) {
    clients := GetStorage()
    conn := new(StubConn)
    clients.Add(5, conn)
    if len(clients.conns) != 1 {
        t.Error("Expected client adding to increment storage map size")
    }
}

It results in compilation error:

cannot use conn (type *StubConn) as type *net.Conn in argument to clients.Add:
*net.Conn is pointer to interface, not interface

But it works if the add function takes parameters as conn net.Conn (values) and make the map hold values instead. So it seems that even if Stubb the interface, the Stubb pointer isn't going to pass as a pointer to the real interface.

Is there a way to pass my StubbConn pointer acting as a pointer to Conn for functions that take pointer to an interface as a parameter?

Even if I'm completely lost and should chance my map to hold actual Conn-values instead of pointers (and please do tell me if I should be doing that), the question holds for unit testing other functions that take pointers to interfaces as params.

mocking angular $element in jasmine

I need to test a directive controller with $element inside. So I've got a function like this one:

function func($event) {
        $element.find('#la-la-la').focus();
}

and render it in the test:

template = $compile(element)($scope);
$scope.$apply();

controller = element.controller('myDirective');

And what I'm trying to do is to test this function inside that controller for the directive.

describe('func method', function testFunc() {
    it('should focus on element', function checkFocusing() {
        controller.func();
        expect(focusSpy).toHaveBeenCalled();
    });
});

Where "focusSpy" is a spy inside mocked $element service. But it seems like if I use $provide.service('$element', ...) it is not found by the test. Injecting it to $scope.$element before compiling doesn't work either. Thank you!

How to get data from console using Unit Test Project

I'm using Selenium WebDriver for C# and want to get username and password from console. My code is:

var username = Console.ReadLine(); 
var password = Console.ReadLine();

// open application
driver.Navigate().GoToUrl("http://myurl");

// enter username and password, press enter
driver.FindElement(By.Id("Username")).SendKeys(username);
driver.FindElement(By.Id("Password")).SendKeys(password);
driver.FindElement(By.Id("Password")).SendKeys(Keys.Enter);

But Console.ReadLine() not working in Unit Test Project.

What is the best way to do it?

Mocking with Substitute.ForPartsOf still goes inside that method

In my UserValidation class I am testing a method which that method is internally calling another method. But I just want to return some fake value for that internal method and move on! But the problem is that it is still actually going inside that method.

The method I want to just give me a mock result is this:

public virtual List<Web_Pharmacy_Users> QueryUsersByEmail(string emailAddress)
{
    var query = (from u in _cactusDbContext.Web_Pharmacy_Users
        where
            (u.Email.Trim().ToUpper() == emailAddress.Trim().ToUpper()
             && u.Active)
        select u);

    return query.ToList();
}

where _cactusDbContext is coming through dependency injection and Web_Pharmacy_Users is a DbSet table.

The way I tried to mock its result is like this below:

    ICactusDbContext fakeDbContext = NSubstitute.Substitute.For<ICactusDbContext>();

    var partiallyFaked = Substitute.ForPartsOf<UserValidation>(fakeDbContext);

    List<Web_Pharmacy_Users> webUsers = new List<Web_Pharmacy_Users>();

    try
    {
        partiallyFaked.QueryUsersByEmail("a@abc.com").Returns(webUsers);
    }
    catch (Exception e)
    {
        var dfgf = e.ToString();
        throw;
    }

But it throws a null exception because it tries to actually run that method so goes to this part of code in _cactusDbContext.Web_Pharmacy_Users and it is null.

I thought it shouldn't even try to go inside and run the actual code. What am I doing wrong?

How can you unit test Leaflet JS maps?

How can you unit test Leaflet JS maps?

Mocha.js test with Chai.js not working in asserting numeric values

I am facing a problem in writing a test case using Mocha and Chai. In the following code value of n is 1. I checked it using console.log(). Though I am testing this value against 0 the test is still passing. Actually it doesn't matter against what value n is tested, the test is passing anyway. What is the problem in it? Can anyone help?

it("Should have 1 variables", function(){                                    
    var variable_count = require("../../lib/variable_count").variable_count; 
    var file = __dirname + '/cases/case_3.json';                             
    jsonfile.readFile(file, function(err, obj) {                                                            
        var n = variable_count(obj);                                                                        
        expect(n).to.equal(0);                                                                         
        assert.strictEqual(n, 0);                                                                           
    });                                                                                                     
});

Can proper OO be used with writing HTML helpers with MVC?

Can proper OO be used with writing HTML helpers with MVC? or is there a deeper reason for holding on to usage of static methods and things that can not be unit tested like TextBoxFor etc. ?

Every tutorial/book/video is using archaic procedural programming methods, on a recent project I was told not to use OO modelling and continue with writing everything in static methods and static helper functions!

Is there a real reason for every sample negating all the OO prinicples just because using helper extensions has to be done as a static method and continuing on using Text Writers line by line? Any OO modelled html components can be unit tested, more clear and concise in intention.

To make the matters worse TagBuilder is used as a mediocre text massaging utility, were as modelling with TagElements (if there was such a thing) and calling render on a parent containing child elements would render the entire DOM. Why is writing line by line is preferred instead of constructing objects that each can be programmatically accessed as specific type or IHTMLElement/ITagElement/IWathever interface?

What am I missing? This is the same method that is used to manipulate an html document loaded into a browser, except that in this case the object are being constructed and rendered into a browser. Delphi had HTML DOM object library in 1999. Why HTMLHelper promotes procedural archaic non unit testable programming?

Manipulating return value of inner function for unit testing?

I am currently trying to write the unit test for some legacy code. In one of my function, it calls another function. According to the return value of the inner function, three branching conditions are present. The code is written in C++ and I am using cxxtest framework. How can I manipulate the return value of the inside function without going into the implementation of it so that I can pass through all the branching condition? I prefer to avoid dependencies between the functions. Is there any way to do this?

Unresolved reference: DaggerTestComponent (Kotlin with Dagger for Test)

When we use Dagger and Kotlin, we'll need the following in our build.gradle dependency

kapt 'com.google.dagger:dagger-compiler:2.0'
compile 'com.google.dagger:dagger:2.0'
provided 'org.glassfish:javax.annotation:10.0-b28'

As stated in http://ift.tt/29obx6o

When I try to perform testing using Dagger, and generate the DaggerTestComponent.builder() as per http://ift.tt/293uTPP or even http://ift.tt/29oaZ0m, in Kotlin language, but have the below error

Error:(14, 25) Unresolved reference: DaggerTestComponent

I found http://ift.tt/293uVHv which explain how to get DaggerTestComponent generated, and try put the below in my dependency.

androidTestApt 'com.google.dagger:dagger-compiler:2.0.1'

Apparently, I think this is for Java and not Kotlin, so the issue persist. Is there a Kotlin version of it? How to get my DaggerTestComponent generated in my Kotlin project?

Google Mock: return Vector

I am new to gtest and gmock framework, i am writing unit test case for application where method return vector.

I want to mock function which is returning vector using gmock, what will be possible EXPECT_CALL syntax for returning vector value.

syntax for my function is as below vector GetStringList();

Please suggest possible solution for this.

How to know which unit tests are calling which functions in code coverage?

I am working on a javascript project. Using mocha for unit tests and istanbul for code coverage. In code coverage I want to know which functions from the source code each test is calling. Is it possible? If yes, how?

How can i run a a unit Test in Apache Camel

I want to know the comand line in maven to run unit tests for Apache Camel. Any help please? Regard

How to write unit tests in C

I need to write a simple unit test that executes on a given .c file. I can't seem to find simple explanations or examples on the web to help me accomplish this. I've seen examples where unit testing frameworks such as cUnit are used.. but is this a necessity? Also, I need the unit test to be executable without using any IDE.

How to get header values in laravel testing

This is how i get response in test Case

$response = $this->call('POST','/api/auth/login',['username'=>'xx','password'=>'xxx'], [/* cookies */], [/* files */], ['HTTP_ClientSecret' => 'xxxx']);

Then we can get response content by like this

$response->getContents()

i want to know how to get response header data ?

Angular 1.5 unit test controller that requires parent component's controller

I'm trying to unit test a (child) controller of an AngularJS 1.5 (with Webpack) component that requires a parent component and a controller from another module.

Child controller structure:

function ChildController () {
  var vm = this;

  vm.searchText = '';

  vm.submit = function() {
    var data = {};
    data['srch'] = vm.searchText;
    vm.parentCtrl.submitTextSearch(data);
  };
}

module.exports = ChildController;

Child component:

var template = require('./child.html');
var controller = require('./child.controller');

var childComponent = {
  require: {
    parentCtrl: '^parent'
  },
  template: template,
  controller: controller,
  controllerAs: 'vm'
};

module.exports = childComponent;

So what I would like to do is to mock out the parentCtrl that's required in the childController's submit()-function. I've been unable to find how to actually do this. I've found some similar child-parent directive solutions and tried those, e.g. injecting the parent controller through fake html-element as described in this child-parent directive example and basically the same stackoverflow solutions with no results. My problems differs at least in the fact that the child and parent controller are in different modules. And I suppose scope-tricks are not that much Angular 1.5-style?

The skeleton of my Jasmine test without my failed mock attempts:

describe('child component', function() {
  describe('child controller', function() {
    var controller;
    beforeEach(angular.mock.module('child'));
    beforeEach(inject(function(_$componentController_) {
      controller = _$componentController_('child');
    }))
    it('should work', function() {
      controller.searchText = "test";
      controller.submit();
    })
  })
})

That results in TypeError: Cannot read property 'submitTextSearch' of undefined. What exactly should I do to mock the parent controller out? With my limited experience in Angular I'm out of ideas.

Can you stop an MUnit test part way through a flow?

I am writing an MUnit test to test a sub-flow is called but once the sub-flow has been called the test tries to route through the rest of the flow. Without mocking various processors this means the test will fail.

Is it possible to stop a test when it reaches a certain processor? I.e. when message processor matches X Stop test?

ODOO [V8] Unit Tests

I'm actually trying to run the unittests I've created thanks to Odoo's documentation.

I've built my module like this :

module_test
- __init__.py
  __openerp.py__
... 
- tests
   __init__.py
   test_1.py

Inside 'module_test/tests/init.py', I do have "import test_1" Inside, 'module_test/tests/test_1.py", I do have : "import tests + a test scenario I've written.

Then I launch the command line to run server, and I add : '-u module_test --log-level=test --test-enable' to update the module and activate the tests run

The shell returns : "All post-tested in 0.00s, 0 queries". So in fact, no tests are run.

I then added a syntax error, so the file can't be compiled by the server, but shell returned the same sentence. It looks like the file is ignored, and the server is not even trying to compile my file... I do not understand why ?

I've checked some Odoo source module, the 'sale' one for example. I've tried to run sale tests, shell returned the same value than before. I added syntax error inside sale tests, shell returned the same value again, and again.

Does anyone have an idea about this unexpected behavior ?

Thank you...!

junit test with dao create and get id

I have this service that I need to create Unit test for:

            SomeObject obj = new SomeObject();

            String objConfig = "<root id=%id% param1="something">....</root>"

            obj.setField1("value1");
            obj.setField2("value2");

            someObjectDao.create(obj);

            Long objId = obj.getId();
            obj.setConfig(objConfig.replace("%id%", objId.toString()));
            someObjectDao.update(obj);

Now, the problem is that in a real case, the DAO create will assign ID on the object, but how do I set the object ID through a Unit test?

Golang - Effective test of multiple packages

I want to execute all tests from my application, now I do it with command:

go test ./app/... 

Unfortunately it takes quite a long time, despite that single tests run quite fast. I think that the problem is that go needs to compile every package (with its dependence) before it runs tests.

I tried to use -i flag, it help a bit but still I'm not satisfied with the testing time.

go test -i ./app/... 
go test ./app/... 

Do you have any better idea how to efficiently test multiple packages.

mardi 28 juin 2016

Test always fails with Test Explorer Run All, but always passes with Debug Test

I have the following piece of code:

public override async Task<string> ExecuteAsync(string googleAuthToken)
{
    string apikeyKeyname = "token";

    dynamic response = await BuildFullApiPath()
            .SetQueryParams(new { token = googleAuthToken })
            .GetJsonAsync();

    string receivedApiKey = ((IDictionary<string, object>) response)[apikeyKeyname].ToString();
    Debug.WriteLine("GetApiKey: received apikey is " + receivedApiKey);

    return receivedApiKey;
}

And the xUnit test for that code:

    [Fact]
    public async void ShouldBeAbleToGetApiKeyFromToken()
    {
        // Arrange
        using (var httpTest = new HttpTest())
        {
            var jsonResponse = JsonConvert.DeserializeObject(@"{""token"":""abcdef""}");
            string expectedApiKey = "abcdef";
            httpTest.RespondWithJson(jsonResponse);
            var api = new GetApiKey();

            // Act
            var receivedApiKey = await api.ExecuteAsync("mockToken");
            output.WriteLine("Received apikey = " + receivedApiKey);

            // Assert
            Assert.Equal(expectedApiKey, receivedApiKey);
        }
    }

The test above only succeeds when I set a breakpoint inside ExecuteAsync(), debug the test (right click on the test in Test Explorer and debug), and step over line by line. But when I press Run All, the test always fail with System.Collections.Generic.KeyNotFoundException : The specified key 'token' does not exist in the ExpandoObject. When I debug the test and step over line by line, receivedApiKey always has "abcdef" as passed in by the unit test, but when I Run, receivedApiKey in the test is always null.

Python 2.7 JavaBridge Error importing jar

Hi and thanks in advance,

I am trying to use python javabridge to to do a unit test that requires me to use a java jar file that has some api classes that I am trying to use. FYI, jar file is in the same directory as the test. ERROR:

# nosetests --with-javabridge  --with-xunit --xunit-file=test.xml jbTest.py
E
======================================================================
ERROR: Failure: ImportError (No module named com.filenet.api.core)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/root/test/jbTest.py", line 6, in <module>
    from com.filenet.api.core import Factory
ImportError: No module named com.filenet.api.core
-------------------- >> begin captured logging << --------------------
javabridge.jutil: DEBUG: Creating JVM object
javabridge.jutil: DEBUG: Signalling caller
--------------------- >> end captured logging << ---------------------

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

code:

import unittest
import os
import javabridge
javabridge.start_vm(run_headless=True)
javabridge.JARS.append("Jace.jar")
from com.filenet.api.core import Factory


class testCE(unittest.TestCase):

     def test_CE(self):
        pass

Use AutoData and MemberData attributes in XUnit test

I'm facing an interesting problem. I found out that the AutoDataAttribute can be use to minimize the "Arrange" part of your test (dependencies passed through the ctor). Awesome!

Example:

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(new Fixture().Customize(new AutoMoqCustomization()))
    { }
}

[Theory, AutoMoqData]
public void Process_ValidContext_CallsK2Workflows(
    [Frozen]Mock<IK2Datasource> k2,
    [Frozen]Mock<IAppConfiguration> config,
    PrBatchApproveBroker sut)
{
   (...)
}

Now i want to use this great feature AND inject my own data into this theory:

[Theory, AutoMoqData, MemberData("Data")]
public void ExtractPayments_EmptyInvoiceNumber_IgnoresRecordsWithEmptyInvoiceNumber(
        [Frozen]Mock<IExcelDatasource> xls,
        SunSystemExcelDatasource sut,
        List<Row> rows,
        int expectedCount)
{
    (...)
}

Problem: AutoData attribute will generate random data for me. The only way I found is to get rid of the AutoData attribute and use MemberData. If I do that, I need to handle object instantiations myself :)...

Is there a way to pass my classes AND some "hard-coded" data at the same time?

Thank u, Seb

angular2 testing framework async testing issue

I have created angular 2 a project and a service with angular-cli and trid to test my service.

But API does not fail in async function although it should fail ;moreover, it just ignores those exceptions.

/* tslint:disable:no-unused-variable */

import {
  beforeEach, beforeEachProviders, describe, xdescribe,
  expect, it, xit, async, inject, injectAsync
} from '@angular/core/testing';
import { SearchService } from './search.service';
import {provide} from '@angular/core';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {XHRBackend, Response, ResponseOptions, HTTP_PROVIDERS} from '@angular/http';

describe('Search Service', () => {
  let searchService: SearchService;
  let mockBackend: MockBackend;

  beforeEachProviders(() => [
    HTTP_PROVIDERS,
    MockBackend,
    provide(XHRBackend, { useClass: MockBackend }),
    SearchService
  ]);

  beforeEach(injectAsync([SearchService, MockBackend], (s, m) => {
    searchService = s;
    mockBackend = m;
  }));

  it('async test', () => {
    setTimeout(() => {
      expect(2).toBe(1);
    }, 3000);
  });

It just ignores those minimal test case.

Then I have read some doc and updated my code as follow.

it('async test with done', (done) => {
  setTimeout(() => {
    expect(1).toBe(1);
    done();
  }, 1000);
});

But this time, the test fails although it should pass. The error is as follow.

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

I change default timeout value to bigger value but it is no effect.

Error: No provider for DirectiveResolver! Angular2 RC2 when trying to use TestComponentBuilder in unit test

I am trying to test my angular2 application. When I add an import to TestComponentBuilder it is throwing an error: Error: No provider for DirectiveResolver!

This is a typescript project using Angular2 RC2.

Here is my spec (test) file:

import { Component, provide, EventEmitter} from '@angular/core';
import { HTTP_PROVIDERS }    from '@angular/http';

import { PreliminaryNotice } from '../models/preliminary-notice-model';
import { IndustryCategoryDynamicLookup } from '../models/industry-category-dynamic-lookup-model';
import { PreliminaryNoticeService } from '../preliminary-notice-service/preliminary-notice.service';
import { ExpandedPreliminaryNotice } from './expanded-preliminary-notice';

import { beforeEachProviders,
    beforeEach,
    inject,
    injectAsync,
    fakeAsync,
    it,
    describe,
    expect
} from '@angular/core/testing';

import { TestComponentBuilder } from '@angular/compiler/testing';

class PreliminaryNoticeServiceMock {
    public preliminaryNoticeSaved: EventEmitter<PreliminaryNotice> = new EventEmitter<PreliminaryNotice>(false);

    public savePreliminaryNotice(preliminaryNotice: PreliminaryNotice) {
        this.preliminaryNoticeSaved.next(preliminaryNotice);
    }
}

describe('expandable preliminary notice tests',
() => {
    let builder: TestComponentBuilder;
    let preliminaryNoticeService: PreliminaryNoticeService;

    beforeEachProviders(() => [
        TestComponentBuilder,
        provide(PreliminaryNoticeService, { useClass: PreliminaryNoticeServiceMock })
    ]);

    beforeEach(inject([PreliminaryNoticeService, TestComponentBuilder],
    (pns: PreliminaryNoticeService, tsb: TestComponentBuilder) => {
        preliminaryNoticeService = pns;
        builder = tsb;
    }));

    it('view invoices expanded',
    (done: () => void) =>
    {
        return builder.createAsync(ExpandedPreliminaryNotice)
            .then(fixture => {
                        let nativeElement = fixture.nativeElement;
                        fixture.detectChanges();
                        fixture.nativeElement.querySelector('showOpenInvoicesHeader').click();
                        fixture.detectChanges();
                        expect(nativeElement.querySelector('showOpenInvoicesContent') === null).toBe(false);
                done();
            });
    });

    it('view log expanded',
    () => {
        expect(false).toEqual(true);
    });
});

Here is the component:

import { Component, Injectable, Inject, EventEmitter, OnInit, Output } from '@angular/core';
import { NgClass } from '@angular/common';
import { PreliminaryNotice } from '../models/preliminary-notice-model';
import { IndustryCategoryDynamicLookup } from '../models/industry-category-dynamic-lookup-model';
import { PreliminaryNoticeService } from '../preliminary-notice-service/preliminary-notice.service';

@Component({
    selector: 'expanded-preliminary-notice',
    inputs: ['preliminaryNotice: preliminaryNotice'],
    templateUrl: 'app/grid/expanded-preliminary-notice.html',
    styles: [
        `
.expanded-preliminary-notice {
    padding: 10px;
}

.bold-span {
    font-weight: bold;
    margin-right: 5px;
}

.pad-left {
    margin-left: 90px;
}

.link-div {
    color:  #1F7A74;
    cursor: pointer;
    width: 300px;
    margin-top: 10px;
    margin-bottom: 10px;
}

.align-left {
    text-align: left;
}

.align-right {
    text-align: right;
}

.border-top {
    border-top: 1px solid black;
}

.border-bottom {
    border-bottom: 1px solid black;
}

.bold-gold {
    color: #A95C15;
    font-weight: bold;
}

table {
    border-collapse: collapse;
}

.backgrounded {
    font-family: 'Arial Regular', 'Arial';
    font-weight: 400;
    font-style: normal;
    font-size: 13px;
    color: #333333;
    text-align: left;
    background-color: #D9D1BD;
}

.number-input {
    width: 75px;
}

.h2 {
    font-family: Arial;
    font-weight: Bold;
    font-size: 22px;
    color: #13294b;
}

.h3 {
    font-family: Arial;
    font-weight: Normal;
    font-size: 20px;
    color: #a6601c;
}

.h4 {
    font-family: Arial;
    font-weight: bold;
    font-size: 18px;
    color: #a6601c;
}

#showPreliminaryNoticeStatus {
    margin-top: 5px;
    margin-bottom: 25px;
}

.thick-hr {
    border: none;
    height: 5px;
    color: #746F63;
    background-color: #746F63;
}

`
    ]
})

export class ExpandedPreliminaryNotice {
    @Output()
    doViewThresholds: EventEmitter<boolean> = new EventEmitter<boolean>(false);

    private preliminaryNotice: PreliminaryNotice;
    private originalPreliminaryNotice: PreliminaryNotice;
    private backgrounColor: string = "transparent";
    private timerToken: any;
    private intervalToken: any;
    private opacity: number = 1;
    protected primaryBusinesses: IndustryCategoryDynamicLookup[] = [
        {
            id: 1,
            industryCategoryName: "Construction",
            industryCategoryDescription: "Construction",
            isLienableFlag: true,
            displaySortOrder: 1
        },
        {
            id: 3,
            industryCategoryName: "Hospitality",
            industryCategoryDescription: "Hospitality",
            isLienableFlag: false,
            displaySortOrder: 2
        },
        {
            id: 2,
            industryCategoryName: "Manufacturing and Logistics",
            industryCategoryDescription: "Manufacturing and Logistics",
            isLienableFlag: false,
            displaySortOrder: 3
        },
        {
            id: 5,
            industryCategoryName: "Retail",
            industryCategoryDescription: "Retail",
            isLienableFlag: false,
            displaySortOrder: 4
        },
        {
            id: 4,
            industryCategoryName: "Transportation",
            industryCategoryDescription: "Transportation",
            isLienableFlag: false,
            displaySortOrder: 5
        },
        {
            id: 6,
            industryCategoryName: "Other",
            industryCategoryDescription: "Other",
            isLienableFlag: false,
            displaySortOrder: 20
        }
    ]; // todo:  pull from service.
    protected noticeStatuses: string[] = ['New', 'Suggested', 'Completed', 'Released']; // todo: pull from service.
    protected doShowStatusLog: boolean = false;
    protected doShowOpenInvoices: boolean = false;
    protected doShowAllOrders: boolean = false;
    protected setThresholdValue: number;

    constructor(private preliminaryNoticeService: PreliminaryNoticeService) {

    }

    ngOnInit() {
        this.preliminaryNoticeService.preliminaryNoticeSaved.subscribe((preliminaryNotice: PreliminaryNotice) => {
            this.preliminaryNotice = preliminaryNotice;
            this.originalPreliminaryNotice = JSON.parse(JSON.stringify(this.preliminaryNotice));
            this.startSaveTimer(2500);
        });
        this.setThresholdValue = this.preliminaryNotice.lienThresholdAmount;
    }

    ngAfterViewInit() {
        //  cheap clone.
        this.originalPreliminaryNotice = JSON.parse(JSON.stringify(this.preliminaryNotice));
    }

    protected getCssClass() {
        return {
            'padding': '10px'
            ,'background-color': this.backgrounColor
        }
    }

    // 1 == stateThreshold, 2 == custom, 3 == don't send.
    protected set noticeSetTo(value: number) {
        this.preliminaryNotice.customerPreliminaryNoticeOption = value;
    }

    protected get noticeSetTo(): number {
        return this.preliminaryNotice.customerPreliminaryNoticeOption;
    }

    protected getInvoiceStyle(isLienable: boolean, textAlign: string) {
        if (isLienable) {
            return {
                "font-weight": "bold",
                "text-align": textAlign,
                "border-bottom": "1px solid lightgray"
            }
        }
        return {
            "font-weight": "normal",
            "text-align": textAlign,
            "border-bottom": "1px solid lightgray"
        }
    }

    public toggleShowPreliminaryNoticeStatusLog() {
        this.doShowStatusLog = !this.doShowStatusLog;
    }

    public toggleShowOpenInvoices() {
        this.doShowOpenInvoices = !this.doShowOpenInvoices;
    }

    public toggleShowAllOrders() {
        this.doShowAllOrders = !this.doShowAllOrders;
    }

    public viewThresholds() {
        this.doViewThresholds.next(true);
    }

    public getStatusLogToggleText() {
        if (this.doShowStatusLog) {
            return "Hide preliminary notice status change log";
        }
        return "Show preliminary notice status change log";
    }

    public getOpenInvoicesToggleText() {
        if (this.doShowOpenInvoices) {
            return "Hide open invoices";
        }
        return "Show open invoices";
    }

    public getAllOrdersToggleText() {
        if (this.doShowAllOrders) {
            return "Hide orders";
        }
        return "Show orders";
    }

    public save() {
        this.preliminaryNoticeService.savePreliminaryNotice(this.preliminaryNotice);
    }

    public undo() {
        this.preliminaryNotice = JSON.parse(JSON.stringify(this.originalPreliminaryNotice));
        this.setThresholdValue = this.preliminaryNotice.lienThresholdAmount;
    }

    private startSaveTimer(time: number) {
        if (this.timerToken) {
            clearTimeout(this.timerToken);
            this.timerToken = 0;
        }
        if (this.intervalToken) {
            clearInterval(this.intervalToken);
        }
        this.opacity = 1;
        this.timerToken = setTimeout(() => this.backgrounColor = "transparent", time);
        this.intervalToken = setInterval(() => {
            if (this.opacity < 0) return;
            this.opacity -= .02;
            this.backgrounColor = "rgba(154, 212, 113, " + this.opacity + ")";
        }, 10);
    }
}

And the template html:

<div [ngStyle]="getCssClass()" id="expandablePreliminaryNotice_">
    <div class="h2"></div>

    <div>
        <span class="bold-span" id="expandPrelimNoticeSettingsSpan">Preliminary notice threshold settings for new orders</span>
        <span class="bold-span" style="margin-left: 125px;">Primary business</span>
        <select id="primaryBusinessSelect" [(ngModel)]="preliminaryNotice.customerJobType">
            <option *ngFor="let primaryBusiness of primaryBusinesses" [value]="primaryBusiness.id"></option>
        </select>
    </div>
    <div id="thresholdsSettingsDiv">
        <input type="radio" name="thresholdGroup" value="1" [ngModel]="{checked: noticeSetTo === 1}" (change)="noticeSetTo=$event.target.value"/>Use state threshold of jobsite
        <div id="viewThresholdDiv" style="display: inline-block" class="link-div" (click)="viewThresholds()">View thresholds</div> <br />
        <input type="radio" name="thresholdGroup" value="2" [ngModel]="{checked: noticeSetTo === 2}" (change)="noticeSetTo=$event.target.value" />Set threshold to <input type="number" [(ngModel)]="setThresholdValue" class="align-right number-input" [disabled]="noticeSetTo != 2"/><br />
        <input type="radio" name="thresholdGroup" value="3" [ngModel]="{checked: noticeSetTo === 3}" (change)="noticeSetTo=$event.target.value" />Do not send notices
    </div>
    <hr />
    <div class="h4"> at </div>
    <!--<div class="h4"></div>-->
    <div>
        <span class="bold-span">Preliminary notice status</span>
        <select id="noticeStatus">
            <option *ngFor="let status of noticeStatuses" [value]="status"></option>
        </select>

        <span class="bold-span align-left pad-left">Lien threshold</span><input type="number" [(ngModel)]="preliminaryNotice.lienThresholdAmount" class="align-right number-input" />

        <span class="bold-span align-left pad-left">Estimated amount</span><input type="number" [(ngModel)]="preliminaryNotice.estimateAmount" class="align-right number-input" />
    </div>
    <div id="showPreliminaryNoticeStatus">
        <div id="showPreliminaryNoticeStatusHeader" (click)="toggleShowPreliminaryNoticeStatusLog()" class="link-div"></div>
        <div id="showPreliminaryNoticeStatusContent" *ngIf="doShowStatusLog" style="width: 450px;">
            <table>
                <thead>
                    <tr>
                        <td class="bold-gold border-bottom" style="width: 120px;">Filing status</td>
                        <td class="bold-gold border-bottom" style="width: 130px;">Date and time</td>
                        <td class="bold-gold border-bottom" style="width: 200px;">Changed by</td>
                    </tr>
                </thead>
                <tbody *ngFor="let log of preliminaryNotice.statusChangeLog">
                    <tr>
                        <td style="border-bottom: 1px solid lightgray"></td>
                        <td style="border-bottom: 1px solid lightgray"> </td>
                        <td style="border-bottom: 1px solid lightgray"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div id="invoicesDiv" class="level-one-no-left-margin">
        <table style="width: 200px">
            <thead>
                <tr>
                    <td colspan="2" class="backgrounded">OPEN INVOICES</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="bold-span align-left">Construction</td>
                    <td class="bold-span align-right"></td>
                </tr>
                <tr>
                    <td class="align-left">Non-Construction</td>
                    <td class="align-right"></td>
                </tr>
                <tr>
                    <td class="align-left border-top">TOTAL</td>
                    <td class="align-right border-top"></td>
                </tr>
            </tbody>
        </table>
        <div id="showOpenInvoices">
            <div id="showOpenInvoicesHeader" (click)="toggleShowOpenInvoices()" class="link-div"></div>
            <div id="showOpenInvoicesContent" *ngIf="doShowOpenInvoices" style="width: 275px;">
                <table>
                    <thead>
                        <tr>
                            <td class="bold-gold border-bottom" style="width: 85px;">Number</td>
                            <td class="bold-gold border-bottom" style="width: 90px;">Date</td>
                            <td class="bold-gold border-bottom" style="width: 100px;">Balance</td>
                        </tr>
                    </thead>
                    <tbody *ngFor="let invoice of preliminaryNotice.invoices">
                        <tr>
                            <td [ngStyle]="getInvoiceStyle(invoice.invoiceJobType.isLienableFlag, 'left')"></td>
                            <td [ngStyle]="getInvoiceStyle(invoice.invoiceJobType.isLienableFlag, 'left')"></td>
                            <td [ngStyle]="getInvoiceStyle(invoice.invoiceJobType.isLienableFlag, 'right')"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div id="ordersDiv" class="level-one-no-left-margin">
        <span class="backgrounded">ALL ORDERS</span><br />
        <div id="showAllOrders">
            <div id="showAllOrdersHeader" (click)="toggleShowAllOrders()" class="link-div"></div>
            <div id="showAllOrdersContent" *ngIf="doShowAllOrders" style="width: 500px; background-color: #00ced1; height: 100px;">
            </div>
        </div>
    </div>
    <hr class="thick-hr" />
    <div class="buttons-div">
        <button (click)="save()" class="primary-button">Save</button>
        <button (click)="undo()" class="secondary-button">Undo</button>
    </div>
</div>

I tried adding an import for the DirectiveResolver and that started me down a rabbit hole of having to add many other items manually, which I am guessing is NOT the correct way to do it.

It has been a while since I have posted a question here so if I am missing something please let me know and I will add it.