samedi 2 juillet 2016

angular2 rc.4: How to inject mocked services (provide() is deprecated)

Since angular 2.0.0-rc.4 release (change log), both beforeEachProviders and provide are deprecated. My question is how can I inject my mocked service inside my component. Here is my beforeEach function which creates a ComponentFixture with overrided providers:

 beforeEach(async(inject([TestComponentBuilder], (tcb)=> {
   builder = tcb;
 })));

 beforeEach(async(inject([], ()=> {
   return builder
    .overrideProviders(MenubarComponent,[provide(MenubarService, {useClass:MenubarServiceMock})])
  .createAsync(MenubarTestComponent)
  .then((_fixture:ComponentFixture<any>)=> {
    fixture = _fixture;
  })
})));

This approach works fine but as I said provide is deprecated.

What is the right way to do this without using provide()?

Create unit tests in ASP.NET core

When I right-click a class in my application code in an ASP.NET MVC 4.6 project then I have this option to create a UNIT Test:

enter image description here

But in my ASP.NET Core (VS2015 Core 1.0.0 Tooling Preview 2) I don't have this option available, when I right-click the class.

I have read that XUnit is now the recommended test framework of choice for ASP.NET Core projects. Is it not possible to use the old good Microsoft Unit Testing Framework?

Are we really forced to use XUnit now?

Update: It looks like there will be a compatible version of the MSTest Framework in the future --> SO Thread. As I don't want to switch to XUnit.

Mocking a Python Standard Library function with and without pytest-mock

For testing purposes I would like to mock shutil.which (Python 3.5.1), which is called inside a simplified method find_foo()

def _find_foo(self) -> Path:
foo_exe = which('foo', path=None)
if foo_exe:
    return Path(foo_exe)
else:
    return None

I'm using pytest for implementing my test cases. Because of that I also would like to use the pytest extension pytest-mock. In the following I pasted an example testcase using pytest + pytest-mock:

def test_find_foo(mocker):
mocker.patch('shutil.which', return_value = '/path/foo.exe')

foo_path = find_foo()
assert foo_path is '/path/foo.exe'

This way of mocking with pytest-mock doesn't work. shutil.which is still called instead of the mock.

I tried to directly use the mock package which is now part of Python3:

def test_find_foo():
    with unittest.mock.patch('shutil.which') as patched_which:
        patched_which.return_value = '/path/foo.exe'

        foo_path = find_foo()
        assert foo_path is '/path/foo.exe'

Sadly the result is the same. Also shutil.which is called instead of specified mock.

Which steps of successfully implementing a mock are wrong or missed in my test cases?

Android Testing - Mocked Parcel returns empty objects

I am Unit testing my android app and I have a class that implements Parcelable. For some reason, when I write a test to check my implementation, the mocked Parcel does not deserialize my object correctly.

This is how I am testing the parcelable implementation:

@Test
public void parcelableWriteReadWorks() {
    Parcel parcel = mock(Parcel.class);
    mRightMassage.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    Massage newMassage = Massage.makeMassage(parcel);
    assertEquals(mRightMassage, newMassage);
}

The assertEquals is throwing a NullPointerException because all the fields in the "newMassage" object are empty.

Can you help me to figure out what is going on?

This is my implementation of the parcelable interface for the class:

    /** Required {@code Creator} implementation for the {@link Parcelable} interface */
public static final Creator<Massage> CREATOR = new Creator<Massage>() {
    @Contract("_ -> !null")
    @Override
    public Massage createFromParcel(Parcel in) {
        return new Massage(in);
    }

    @Contract(value = "_ -> !null", pure = true)
    @Override
    public Massage[] newArray(int size) {
        return new Massage[size];
    }
};


/**
 * Constructor created to implement the {@link Parcelable} interface. Reads data from a parcel
 * and includes it as the member fields.
 */
protected Massage(Parcel in) {
    bodyParts = in.readString();
    description = in.readString();
    duration = in.readString();
    headline = in.readString();
    intensity = in.readInt();
    name = in.readString();
    posterPath = in.readString();
    price = in.readInt();
}

/**
 * Describe the kinds of special objects contained in this Parcelable's
 * marshalled representation.
 *
 * @return a bitmask indicating the set of special object types marshalled
 * by the Parcelable.
 */
@Contract(pure = true)
@Override
public int describeContents() {
    return 0;
}

/**
 * Flatten this object in to a Parcel.
 *
 * @param dest  The Parcel in which the object should be written.
 * @param flags Additional flags about how the object should be written.
 *              May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
 */
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(bodyParts);
    dest.writeString(description);
    dest.writeString(duration);
    dest.writeString(headline);
    dest.writeInt(intensity);
    dest.writeString(name);
    dest.writeString(posterPath);
    dest.writeInt(price);
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Massage massage = (Massage) o;

    return intensity == massage.intensity && name.equals(massage.name)
            && bodyParts.equals(massage.bodyParts);
}

@Override
public int hashCode() {
    int result = name.hashCode();
    result = 31 * result + intensity;
    result = 31 * result + bodyParts.hashCode();
    return result;
}
}

JQuery, Jasmine: How to unit test select, open, render functions of autocomplete

We have a Angular 2 component which consists of JQuery autocomplete. The high level implementation details inside ngOnInit, is as follows -

this.autocomp = $(this.elementRef.nativeElement).children().eq(0).autocomplete({
source:    //implementation details
select:    //implementation details
open:      //implementation details
});
//rendering implementation

I understand we should try and avoid UI details for our unit testing. However, still wanted to understand what I can unit test here? I am interested in a way to unit test/access source, select, open and rendering section.

Our template URL is very basic and consists of an Input and Span.

Thanks in advance.

vendredi 1 juillet 2016

can i set a base url for expect()

My restangular call has a baseUrl set in a config file to "http://localhost:3000/". So a call like

Restangular.all("awards").customPOST(award)

calls at baseUrl+"awards"

Now when i write a test for this, i have to write

httpBackend.expectPOST("http://localhost:3000/awards")

But later if this baseUrl changes, i will have to change it in a lot many .expect() methods.

Is there anyway to set a baseUrl for the expect method, in a config file somewhere?

So that the expect method something like-

httpBackend.expectPOST(baseUrl + "awards");

So that any change in the baseUrl does not require any chnage in the expect() method?

How do I get pytest to run all functions as test

I have looked around and I can't find a pytest.ini flag to pass in that says the equivalent of

def test_one():
   # you run this by default

def two():
   # despite not having test in the name you should also run this

reason: test function name lengths are getting to long when I'm being descriptive with naming and frankly it seems anti dry.